C Material
C Material
COLLEGE OF ENGINEERING
1
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
ALU :-
It carries out all arithmetic operations like addition, subtraction,
multiplication and division.
It also performs all logical operations.
OUTPUT DEVICES:
Display screen/Visual display unit/Monitor
- Monochrome
- Colored
MEMORY UNIT:-
It is used to store programs and data
It is mainly two types, they are
(1) main memory (or) primary memory/Immediate Access Storage(IAS)
which is part of CPU
(2) Auxiliary Memory/ Secondary Storage, which is External to the CPU.
INPUT DEVICES:-
Key Board – It is most commonly used input device.
Mouse – It is used to position the cursor on the screen.
Track ball – It is a mouse variation, essentially a mouse lying on its back.
Light Pen – you move the pointer and select items on the display screen by
directly pointing to the objects on the screen with the pen
Touch Screen
2
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Memory:
Memory is used to store , programs and data
It is mainly two types
o Primary/main/Immediate Access Storage(IAS)
o Auxiliary memory/Secondary Storage
Main Memory
It is also called as primary memory and it is available inside the CPU
Just entered data and currently using data is available in the memory. It is a fast
memory, made up of large number of cells
Different types of primary memory is
1) RAM ( Random Access Memory)
All the data entered into the system is directly stored in RAM. The users have direct
access to their part of memory i.e. the user can read and write into this memory
Secondary Storage:
It is also called as External Storage Devices
The main purpose of the external storage is retain data and programs for further
use
If information is stored in an external storage medium then the operator can
retrieve it as and when required, thus avoid repeat typing.
It is now volatile memory ( permanent)
The popular external storage devices are
(1) Magnetic tapes.
(2) Magnetic disks.
Magnetic tapes
3
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
It provides serial access. Therefore you have to read all the previous records to
reach a particular record.
information can be erased by recording new information in its place
the tape is ferromagnetic coating on a plastic base and is similar to the tape used
in tape recorder
Magnetic disks
It allows direct access but can also be used in serial mode if required
Each disk consists of a number of invisible concentric circles called tracks. each
track further divided into sectors
Magnetic disks are two types
(1) Floppy disk: - this is the most common storage medium used on personal
computers. Information can be recorded or read by inserting it into a disk drive
connected to the computer.
(2) Hard Disk:- it is used for storing large volume of information. These are very fast in
reading and writing and storing than floppy disk.
Numeric codes: - when 0-9 decimal digits were coded in binary using a sequence of 0’s
and 1’s the system is called as a numeric coding system. Ex: BCD
ASCII ( American Standard Code For Information Interchange) 7 – bit range 0-127
EBCDIC (Extended Binary Coded Decimal Interchange) 8-bit range 0-225
UNICODE defines a fully international characters set that can represent all of the
characters in all human languages
Generally Unicode characters are represented by escape sequences. It is 16-bit
I.e. 2 bytes and it ranges from 0 to 65,536.
High-level languages (HLL) :-
A Set of languages developed which are very close to our native languages, such
are called as HLL. These are designed that to provided high-level control structures, i/o
facilities, hardware independent and soon.
Ex:- Basic , Cobal , Fortran, Pascal.
Advantages:-
(1) easy to learn and easy to understand than machine or assembly language
(2) less time to write
(3) Easy to maintain.
(4) It is better to documentation.
Hardware: - it is a term used to represent the physical and tangible components of the
4
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Software: - The set of instructions is called as a program. These set of programs are
called Software.
The hardware can’t function without software and software is created by people
Types of software
(1) System Software
(2) Application Software
System Software: - System Software includes all routines that inside the computer
memory and helps the user to write or execute application programs. This facilities the
communication between user and computer
Ex: - Assembler, Compiler, Interpreter, Editors.
Application Software: - Application programs are written for solving a specific problem.
Ex: - Word Processing, billing etc.
Translators: - Translators are software that accepts one language as input and convert it
into another language. the input for any translator is called source language (code) and
output of any translator is called as object language (code).
Compiler: - It is s/w, which accepts the High-level language program as input and
produces the machine code as output.
Assembler: - it is software which accepts the assembly language as i/p and produce
machine code as o/p.
5
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Properties of Algorithms:-
(1) input:- zero or more inputs
(2) output – at least one quantity is produced
(3) Definiteness – each instruction is clean and unambiguous.
(4) Finiteness – the algorithm should terminate after a finite number of steps. It
should not enter into infinite loop.
(5) Effectiveness: - each operation must be simple and should complete in a finite
time.
Algorithm can be written in English like sentences. Algorithm written in English like
language is called pseudo code.
6
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Flowchart:-
A Flowchart is a practical representation of an algorithm that uses boxes of
different shapes to denote different types of instructions.
A flowchart shows the flow of operations in pictorial form, any error in the logic of the
problem can be detected very easily.
Flowchart symbols:-
A few symbols are needed to indicate the necessary operations in a flowchart. These
symbols have been standardized by the ANSI(American National Standard Institute).
1) Terminal:- The terminal (oval) symbol as the name implies is used to indicate the
beginning <START>, ending <STOP> and pause <HALT> in the program logic flow.
4) Flow lines:- Flow lines with arrow Heads are used to indicate the flow operations i.e.
the exact sequence in which the instructions are to be executed.
7
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
6) Connectors: - if a flowchart becomes very long the flow lines start crises crossing
at many places that cause confusion and reduce understandability of the flowchart.
----------------
8
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
inc.
‘c’ is a middle level language, because it combines the best features of high-level
languages with the control and flexibility of assembly language.
‘c’ is a general purpose structured programming language that has much in
common with the best of the HLL
Features and Applications of ‘c’ language:-
c is general purpose structured programming language
c is powerful efficient, compact and flexible.
C is highly portable
C is a robust language whose rich set of built in functions and operators can be
used to write any program.
C is well suited for writing system software as well as application programming.
C has the ability to extend itself. We can continuously add our own functions to the
existing ‘c’ library functions.
‘c’ programs can be run on any of the different computer with little or no alteration.
C is widely available commercial ‘c’ compilers are available on most personal
computers, mini and mainframes.
C language allows to a memory location with the help of printer which holds the
address of the memory location.
C language allows dynamic memory allocation of memory i.e. a program can
request the OS to allocate/release memory.
C language allows manipulations of data at the lowest level i.e. bit level
manipulations.
C is a case-sensitive language.
Function1
Function 2
o A ‘c’ Function 3 program is
a group of building
9
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
The sub program section contains user defined functions that are called in the
main() function.
o User defined functions are generally placed immediately after the main
function.
My First “c” program:
1. /* My First c Program */
2. main()
3. {
4. /* prints the string */
5. printf(“welcome to c world \n”);
6. }
The first and fourth lines are commented lines. These are used in a program to
enhance its readability and understanding.
Comment lines are not executable statements and anything between /* and */
ignored by the compiler.
These comment lines can be inserted whenever we want.
The second line indicates the system that the name of the program in main() and
the execution begins at this line.
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
The main() is a special function used by ‘c’ to tell the computer where the
program starts.
Every program must have exactly one main function.
If we have more than one main() function the compiler cannot know where the
program begins.
The empty pair of parenthesis immediately following main indicates that the
function has no arguments.
The opening brace ‘{‘ in the third line marks the beginning of the function main
and the closing braces ‘}’ is the last line indicates the end of the function.
The statements between these two braces are the function of the body. Here the
function body consist of 2 statements one is comment line and another is printf
line is an executable statement.
The printf function to be printed out every thing which appears in between
quotation marks, here the o/p will be “ welcome to c world”.
Executing a ‘c’ program under MS-DOS system:
C program execution involves the following series of steps.
(1) Creating the program: - the text of a program is called the source code, is a
sequence of statements to be executed by the machine. This source code is usually
stored in files with the extension .c.
(2) compiling and Linking of the program :- before a program is made to run, it must
be translated by the compiler to give .OBJ files and then linked by the linker to give
.EXE file
3) Executing the program: - The extension of executable codes is .EXE. A ‘c’ program
with an extension .EXE can be run in DOS prompt mode.
‘C’ tokens:
The smallest individual units in a program are called Tokens. The ‘c’ tokens are
classified as (1) key words (2) Identifiers (3) constants (4) operators (5) Strings.
Character Set:- The characters that can be used to form words, numbers, expressions ,
data types, constants, variables and key words.
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Constants:- constants are fixed values that do not change during the extension of a
program.
Ex: The equation 5x + 2y = 45.
Here 5,2,45 cannot change, these are called constants. Where as quantities x and
y can vary or change hence these are called variables.
Constant classification:
Real constants:
real constants are constants which are having decimal points,
real constants can be represented in 2 forms,
(1) Fractional. (2) Exponential.
Fractional form:
Rules to be followed to write real constants in fractional form.
It is same as for integer constant expect
Fractional form should have at least one decimal point.
It ranges from -3.4 e 38 to 3.4 e 38.
Valid Invalid
-3.6 -3.6*7
+6.99 -6. 7
Exponential form:
A real constant in exponential form is represented in 2 parts
(1) Mantissa part (2) Exponent part.
Rules: 1) The mantissa & exponent part is separated by e.
2) The mantissa part can be +ve or –ve.
3) Its default sign is +ve.
4) The exponent part must contain at least one digit.
5) The exponent can be either +ve or _ve.
6) Special symbols, blank space etc are not allowed.
Valid invalid
5.5 e 3 1.1*2
0.01 e 25 1e2
Character constant:-
These are combination of characters, digits, special symbols etc.,
12
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Valid invalid
‘a’ “abc”
‘1’ ‘a”
‘+` ‘12”
Valid invalid
“abc” ‘xyz”
”a123” ‘1’
“1/56”
Difference A single character in c is having associated ASCII value but string constant
is not having ASCII value.
ASCII American Standard Code for Information Interchange.
13
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
In exponential form of representation the real value will represents in two parts. The
part appearing before ‘e’ is called mantissa, where as the part followed is called
exponent.
Integer
(coef) e ( Integer) = (coef) X 10
Variable: - A variable is a data name which can be used to store a data and a variable
may take different values at different times, during execution.
Rules:
1) A variable name is any combination of 1 to 8 alphabet digits or underscore.
2) The first character in the variable name must be an alphabet.
3) No commas, blank spaces are not allowed.
4) No special symbol other than under score is used to form a variable.
Ex: Basic_pay, Net_sal, month_sal
Declaration of Variables:
A variable with a global scope is accessible to all statements in a program but the one
with local scope is restricted to be accessed by only certain selected statements in the
program, in which it is defined.
Global variable are declared outside all functions where as local variables are defined
inside a function.
14
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
x=y=z=45;
a=b=c=temp;
15
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
main()
{
printf("%d+%d=%d\n",10,20,10+20);
printf("%d-%d=%d\n",10,20,10-20);
printf("%d*%d=%d\n",10,20,10*20);
}
OUTPUT:
10+20=30
10-20=-10
10*20=200
ex 5) Write a program to print following format
There are 365 days in a year
3.14 is the pi value
+ is an operator
good morning.
main()
{
printf(“There are %d days in a year\n,365”);
printf(“%f is the pi value\n”,3.14);
printf(“ %c is an operator”,+);
printf(“%s”,good morning);
` }
Scanf() function:
scanf() is used to read values from the key board.
Syntax: scanf(“format specifiers”,&arg1,&arg2,……&argn);
(or)
Syntax: scanf(“format specifiers”,&var1,&var2,……&varn);
Ex 1) main()
{
int a=10;
float b=3.14;
char c= ‘+’;
printf(“a=%d\n b=%f\n c=%c”,a,b,c);
}
Write a program to read integer, float, character values from keyboard and print them.
main()
{
int a;
float b;
char c;
printf("enter the integer value\n");
scanf("%d",&a);
printf("enter the float value\n");
scanf("%f",&b);
printf("enter the character value\n");
scanf(" %c",&c);
printf("a=%d b=%f c=%c",a,b,c);
}
OUTPUT:
enter the integer value
9
16
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Data Types:-
Each data type has predetermined memory requirement and an associated range
of values.
Each programming language has its own data types.
ANSIC Supports 4 types of data types
1) Primary (Fundamental) Data Type.
2) User – defined Data Type.
3) Derived Data Types.
4) Empty Data Set.
All ‘c’ compiler support 4 Fundamental data types, namely Integer (Int),
Character (char), Floating Point (float) and Double-precision floating point (double).
Integer: - ‘c’ provides three different types of integers. They are int, short and longint.
The difference between these 3 integers is the no. of bytes to occupy the range of values.
17
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Float: - like integers floats are divided into 3 types. They are float, double and
Long double. The differences between these 3 floats are the no of bytes to occupy and
the range of values.
Characters:- A char is a data type which can store an element of machines character set
and will occupies 1 byte. It is two types, they are signed char and unsigned char.
The differences between these two types are the range of values.
User defined data types:- c supports a feature known as “type definition” that allows
users to define an identifier that would represents an existing data type.
the enumerated variables v1,v2,……vn can only have one of the values
value1,value2,……..valuen.
18
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
19
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
int a,area;
printf(“enter the side of the square \n”);
scanf(“%d “,&a);
area=a*a;
printf(“area=%d”,area);
}
Type Qualifiers: - Short, long, sign or unsigned identifiers may precede some of the
scalar data types to specify the number of bits used for representing the respective type
of data in memory. They are known as qualifiers or modifiers. Suppose 16 bits used to
represent an integer in a system, then the most significant bit is used as sign bit and
other 15 bits are used for representing the magnitude. In the case of signed int as shown
below.
(a)
15 14…………………1 0
sign
bit MAG
0-14 bits
(b)
magnitude
15-0.
In the case of unsigned bit all the 16 bits are used for the magnitude representation.
The following table shows the qualifiers and data type representations.
Types of operators:
In ‘c’ operators can be classified into various categories based on their utility and action.
A list of operators types is given below
20
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Arithmetic operators.
Relational operators.
Logical operators.
Assignment operators.
Increment and Decrement operators.
Conditional operators.
Bitwise operators.
Comma operators.
Arithmetic operators : it can perform arithmetic operations and can be classified into
unary and binary arithmetic operators. It can operate on any built-in data type.
(2) #include<stdio.h>
main()
{
int month,days;
printf(“enter the number of days \n”);
scanf(“%d”,&days);
months=days/30;
days=days%30;
printf(“ months is %d days are %d”,months,days);
}
21
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
P = a/b = 3.5000
Q= b/a = 0.285714
R = a+b = 18.0000
Mixed Mode arithmetic:- in this mode, if either of the operands is real, the resultant
value is always a real value.
Ex: 35/5.0 = 7.0
Here 5.0 is a double constant, 35 is converted to a double and result is also a double.
Relational Operators:-
Arithmetic operators are used to evaluate arithmetic expressions, relational operators
are used to compare arithmetic, logic and character expressions.
Each of these operators compares their left hand side with their right hand side.
The whole expression involving the relational operator then evaluates to an integer.
It evaluates 0 if the condition is false, and 1 if it is true.
Sequence of operators and operands evaluated to a single value.
Operator Meaning
< Lessthan
<= Lessthan (or) Equal to
> Greaterthan
>= Greaterthan(or)Equal to
== Equal to
!= Not Equal to
Ex:- #include<stdio.h>
main()
{
int I,j;
printf(“enter two values \n”);
scanf(“%d %d”,&I,&j);
if(i==j)
pritf(“both are equal \n”);
else
printf(“both are not equal \n);
}
Logical operators:
it is used to compare or evaluate logical and relational expressions. There are 3
logical operators in c.
Operator meaning
&& logical AND.
|| logical OR.
! logical NOT.
An expression involving && and || is some times called compound expression, since
the expression involves two other expressions, i.e. each of these operators (&& and ||)
take two expressions, one to the left and another to right.
22
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Logical NOT:- the ! Operator takes single expression and evaluates to true if the
expression is false, and evaluates to false if the expression is true.
The ! Operator is convict to use when you want to test whether the value of a variable is
zero.
If(!i)
Printf(“the value of I is zero \n);
The increment and decrement operators are very useful in ‘c’ language. These are
extensively used in for and while loops.
The syntax is ++<variable> --<variable>
<variable>++ <variable>--
The operator ++ adds 1 to the operand and – subtracts 1 from the operand. These
operands manifest in two forms i.e. prefix and postfix.
Ex: the ++ operator can be used in two ways.
++m and m++ (these two are different operations).
The expression ++m will increment first, and then this value is assigned to n, resulting
in having the same value.
main()
{
Int n,m=1;
n=m++;
printf(“ postfix operation :n=%d”,m=%d\n”,n,m);
}
postfix operation n=1,m=2
The expression m++ will first evaluate the value of m, resulting is 1 being assigned to
n and then the value of m being incremented to 2.
Bitwise operators:
23
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
A bitwise operator operates on each bit of data. These operators are used for testing,
complementing or shifting bits to the right or left.
Usually these operators are not useful in cases of float and double variables.
Operator Meaning
& Bitwise AND.
| Bitwise OR.
^ Bitwise XOR.
<< Left Shift (Shift Left).
>> Shift Right.
~ compliment.
Bitwise AND: - c = a & b;
Each bit in ‘c’ will be 1 only if the corresponding bits in both a and b are 1.
a = 1101 13
b = 0111 7
------------
a&b= 0101
------------
Bitwise OR: - c = a | b;
‘a’ bit in c will be 1 whenever at least one of the corresponding bits in a or b is 1
a = 1101 13
b = 0111 7
------------
a/b= 1111
------------
Bitwise XOR: - c = a ^ b;
a = 1101 13
b = 0111 7
------------
a^b= 1010
------------
Left Shift Operator: - The left-bit Shift operator, << is a binary operator.
C= a<<3 a = 1101 1101
1110 11010
0111 110100
1011 0110,1000
Right Shift Operator:- The Right Shift operator, >> is a binary operator.
a= -3 0011
24
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
1100
------
1
------
1101
------
’s
(1) To find 2 complement
Complement to the given number.
And add 1 to complement number.
(Condition)?(expression 1):(expression 2)
Larger = i > j ? i : j ;
Here i > j is condition for testing
? mark is conditional operator
i is for expression1.
j is for expression2.
if condition is true it returns first expression and condition is false it returns second
expression
Special operators:-
Comma operator:- A set of expressions separated by comma is a valid construct in the
‘c’ language.
Ex: int i , j;
Here I and j are declared as integers.
Consider the following statement that makes use of the comma operator.
25
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
i = ( j = 3 , j + 2);
the right hand side consists of two expressions separated by comma. These
expressions are evaluated from left to right.
First the value 3 is assigned to j and then the expression j + 2 is evaluated.
The value of the entire comma-separated expression is the value of the right most
expression. Hence the value assigned to i would be 5.
Ex: c= ( a = 10, b =20 , a + b);
First a =10 , b = 20 and a + b = 30 is assigned to c.
Other Operators:
Sizeof:- The operator sizeof gives the datatype or the variable in terms of bytes occupied
in the memory. The sizeof operator returns the no. of bytes the operand occupies in
memory. The operand may be a variable, a constant or a data type.
Address of operator:- The address of operator (&) returns the address of the variable.
The operand may be a variable, a constant
m= &n;
here address of n is assigned to m. this m is not an ordinary variable, it is a variable
which holds address of another variable.
Value at address operator:- The value at address operator (*) returns the value stored at
a particular address. The value at address operator is also called indirection operator.
Ex: x = *m;
Here the value at address of m is assigned to x and m is going to hold the address.
TYPE CONVERSION:
The process of converting one data type value into another data type is called Type
conversion. This is two types
(1) Implicit / coercion.
(2) Explicit / Type casting.
Implicit type conversion:- The process of converting one type value into another value
implicitly by the compiler is called implicit type conversion (or) coercion.
Explicit type conversion:- The process of converting one type into another value explicitly
by programmer is called Explicit type conversion (or) type casting.
Type cast operator:- ‘c’ permits mixing of constants and variables of different types in an
expression, but during evaluation, it follows a definite rule of type conversion.
In an expression, if two operands are of different types, then the lower type value is
automatically converted in higher type. This process is implicit type conversion (or)
automatic type conversion (or) type coercion, but in some situations we need to convert
one type value into another explicitly. This process is known as explicit type conversion
(or) type casting.
Syntax: ( type name) expression;
main() main()
{ {
int a; char x;
26
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
a=(int)’a’; x=(char)65;
printf(“ %d”,a); printf(“ %c”,x);
} }
O/P – 97 O/P – A
main()
{
int a=10;float b=3.14;
printf("value of a is %d \n",a);
printf("address of a is %u \n",&a);
printf("value of b is %f \n",b);
printf("address of b is %u \n",&b);
}
OUTPUT :-
value of a is 10
address of a is 3221207028 (Assumption)
value of b is 3.140000
address of b is 3221207024( Assumption).
main()
{
int a=10;float b=3.14;
printf("value of a is %d \n",*(&a));
printf("address of a is %u \n",&a);
printf("value of b is %f \n",*(&b));
printf("address of b is %u \n",&b);
}
OUTPUT:-
value of a is 10
address of a is 3221210948
value of b is 3.140000
address of b is 3221210944
Assume ‘k to be an integer variable and ‘a to be float variable then the values of k and
a for the following are
27
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
int a,b,c,max;
printf("enter 3 numbers \n");
scanf("%d %d %d", &a,&b,&c);
max=(a>b)&&(a>c)?a:(b>c)?b:c;
printf("maximum number is %d",max);
}
OUTPUT:
enter 3 numbers
3
7
9
maximum number is 9.
OUTPUT:
a=10
a=11
a=12
OUTPUT:
a=10.900000
a=9.900000
a=8.900000
28
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
int a=10,b;
b=a++;
printf("a=%d b=%d\n",a,b);
b=++a;
printf("a=%d b=%d\n",a,b);
}
OUTPUT:
a=11 b=10
a=12 b=12
OUTPUT:
a=8.900000 b=9.900000
a=9.900000 b=8.900000
6) Write a program for sizeof() operator.
main()
{
int a=10;float b=5.6; char c='*';
printf("size of(a)=%d\n",sizeof(a));
printf("size of(b)=%d\n",sizeof(b));
printf("size of(c)=%d\n",sizeof(c));
}
OUTPUT :
size of(a)=4
size of(b)=4
size of(c)=1
main()
29
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
int a=10,b=20;
printf("a<=b:%d",a<=b);
}
OUTPUT:
a<=b:1
main()
{
int a=20,b=20;
printf("a==b:%d",a==b);
}
OUTPUT:
a==b:1
main()
{
int a=-10;
printf("a=:%d\n",a);
printf("!a=%d\n",!a);
printf("!!a=%d\n",!!a);
}
OUTPUT:
a=:-10
!a=0
!!a=1
long int l;
x=l/i+i*f–c
30
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
1) If one of the operands is long double, the other will be converted to long double
and result will be long double.
2) else if one of the operands is double, the other will be converted to double and
the result will be double.
3) else if one of the operands is float, the other will be converted to double and the
result will be float.
4) else if one of the operands is unsigned long int, the other will be converted to
double and the result will be unsigned long int.
5) else if one of the operands is long int, and the other is unsigned int then
a) if unsigned int can be converted to long int, the unsigned int operand will be
converted as such and the result will be long int.
b) else both operands will be converted to unsigned long int and the result will be
unsigned long int.
6) else if one of the operands is long int, the other will be converted to double and
the result will be long int.
7) else if one of the operands is unsigned int, the other will be converted to double
and the result will be unsigned int.
example:
31
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
3 * Multiplication LR
/ Division LR
% Modulus LR
4 + Addition LR
- Subtraction LR
5 << Left shift LR
>> Right shift LR
6 < Less than LR
> Greater than LR
<= Less than or equal to LR
Grater than or equal to
>= LR
7 == Equal to LR
!= Not equal to LR
8 & Bitwise AND LR
9 ^ Bitwise XOR LR
10 | Bitwise OR LR
11 && Logical AND LR
12 || Logical OR LR
13 ?: Conditional RL
14 = += -= *= /= Simple and compound RL
%= >>= <<= &= assignment
^= |=
15 , Comma LR
Ex: x = 20, y = 5;
If ( x == 10 + 15 && y <10)
If( x == 25 && y<10)
32
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Preprocessor commands are also known as preprocessor directives. they begin with
# symbol. Some of the preprocessor directives are
(1) macro expansion.
(2) file inclusion.
write a program to find min of two numbers if first no is less than the second no.
then print ‘1’ other wise print ‘0’.
A) #include<stdio.h>
#define true 1
#define false 0
main()
{
int a,b;
printf("enter two numbers\n");
scanf("%d %d",&a,&b);
(a<b)?printf("%d",true):printf("%d",false);
}
OUTPUT:
enter two numbers
3
5
1
OUTPUT:
enter two numbers
5
3
0
#include<stdio.h>
#define AND &&
#define OR ||
33
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
main()
{
int a=10,b=20,c;
c=a>b AND b<=20 OR a!=10;
printf("%d",c);
}
OUTPUT:
0
#include<stdio.h>
#define P printf
#define S scanf
main()
{
int a;
P("enter a number\n");
S("%d",&a);
P("a=%d",a);
}
OUTPUT:
enter a number
9
a=9.
OUTPUT:
HELLO GOOD MORNING
HELLO GOOD MORNING
#include<stdio.h>
#define LINE printf("one\n");printf("two\n");printf("three\n");
main()
{
LINE;
}
OUTPUT:
one
two
34
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
three
#include<stdio.h>
#define LINE {printf("one\n");printf("two\n");printf("three\n");}
main()
{
LINE;
}
OUTPUT:
one
two
three
File Inclusion:
#include directive is used for file inclusion.
#include directive causes of one file to be included in another file.
In general we write
#include<stdio.h> or #include”stdio.h”
This statement causes entire contents of the file to be replaced in the program at that
point. In general a file to be included is having .h extension.
Files to be included in our program are header files, because they contain statements
which when declared replaces their contents at the beginning of our program.
35
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
#include<math.h>
main()
{
float p,r,ci,si;
int n,t;
printf("Enter Principle Amount\n");
scanf("%f",&p);
printf("Enter the rate of Interest\n");
scanf("%f",&r);
printf("Enter the number of years\n");
scanf("%d",&n);
printf("Enter the number of times the interest compounded per year\n");
scanf("%d",&t);
si=(p*n*r)/100;
ci=p*pow(1+(r/n),n*t);
//p=principle amount
//r=annual nominal interest rate(as decimal)--r/100
//n=the number of time the interest is compounded per year
//t=the number of years
//ci=amount after time t
//sample data p=1500,r=0.043,n=4,t=6then ci=1938.84
printf("the simple interest is %f\n",si);
printf("The compound Interest is %f\n",ci);
}
36
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
OUTPUT:
enter a charecter
r
114 is not a digit.
main()
37
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
char ch;
printf("enter a charecter\n");
scanf(" %c",&ch);
(ch>=65 &&ch<=90)?printf(" %c is in upper case\n",ch):printf(" %c is not in
upper case\n",ch);
ch=ch+32;
printf("after conversion in lower case ch=%c\n",ch);
}
OUTPUT:
enter a charecter
S
S is in upper case
after conversion in lower case ch=s
OUTPUT:
enter a charecter
k
k is not in upper case
after conversion in lower case ch=ï
#include<stdio.h>
main()
{
char ch;
printf("enter a chrecter \n");
scanf(" %c",&ch);
ch=ch+32;
printf("after conversion ch=%c\n",ch);
}
OUTPUT:
enter a chrecter
K
after conversion ch=k
main()
{
char ch;
printf("enter a chrecter \n");
scanf(" %c",&ch);
ch=ch-32;
printf("after conversion ch=%c\n",ch);
}
OUTPUT:
enter a chrecter
k
38
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
7. main()
{
Int a=65;
printf(“value of a is =%d”,a);
printf(“corresponding character is a=%c”,ch);
}
OUTPUT:
a=65
A
The function getchar() is used to read a single character from the key board.
This function returns the integer value of the character in the machines character
code. If the system uses the ASCII character code, then the ASCII value of the character
is returned.
The general format for using this function is
variable = getchar();
Where the variable may be either int or char data type. The getchar() function does not
take any argument.
39
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Putchar(variable);
Where the variable may be represented by an integer constant or a character constant.
Ex: char c;
C=getchar(); putchar(c); putchar(65);
Input data can be entered in to the computer from a standard input device by means of
the ‘c’ library function scanf.
This function can be used to enter any combination of numerical values,
single characters and strings. This function returns the no.of data items that have been
entered successfully.
The general format for scanf() function is
Scanf(“control_string”,argument_list);
40
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
getchar():- This function is used to read a single character from the key board. This
function does not requires any arguments. So, it is followed by empty parentheses.
Ex:- main()
{
char ch;
ch = getchar();
printf(“ %c”,ch);
}
OUTPUT:
a
a.
getch():- This function is used to read a single character from the key board. But it does
not echoes the given character on the screen and also it does not require enter key to
pressed.
Ex: main()
{
char ch;
ch = getch();
printf(“ ch=%c”,ch);
}
OUTPUT
Ch = a
getche():- This function is used to read a single character from standard input device
i.e. keyboard. Like getch() it doesn’t required any enter key to be pressed. Unlike getch()
it echoes the given character on the screen.
Ex: main()
{
char ch;
ch = getche();
printf(“ch=%c”,ch);
}
OUTPUT:
ch=a
ch=a
gets():- The gets() is used to read a string of values (or) no. of characters from the
keyboard.
41
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Syntax: gets(string_name);
#include<stdio.h>
main()
{
char name[20];
printf(“Enter name of a person”);
gets(name);
printf(“name is=%s”,name);
}
output:
Enter the name of a person
Sachin
Name is =sachin
Scanf() stops reading when it gets a space or when it reads a space, but gets()
reads characters including spaces but it stops reading when its gets a new line
characters. Gets() reads new line character and in the place of new line character it
replaces null character.
Putchar(): The putchar() is used to output or to print a single character on the screen.
Syntax: putchar(character_variable);
Putchar(‘character_constant’);
Ex:
#include<stdio.h>
main()
{
putchar(‘a’);
putchar(‘=’); output: a=0
putchar(‘0’);
}
puts():This function is used to output or to print string of values or group of characters
on the screen.
Syntax: puts(string_name);
Puts(“string_constant”);
Ex:
#include<stdio.h>
main()
{
42
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
#include<stdio.h>
main()
{
int a,b,c;
printf(“Enter 3 numbers:”);
scanf(“%3d%3d%3d”,&a,&b,&c);
printf(“a=%d\n b=%d\n c=%d\n”,a,b,c);
}
output:
123 456 789 12 345 678 1 234 5678
a=123 a=12 a=1
b=456 b=345 b=234
c=789 c=678 c=567
main()
{
char name[20];
43
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf(“Enter a name:”);
scanf(“%5s”,&name);
printf(“%s”,name);
}
output:
ANILKUMAR
ANILK
ANIL KUMAR
ANIL
scanf() can also be used to restrict a set of values when we are inputting some
characters.
main()
{
char name[20];
scanf(“%[aeiou]”,name);
printf(“%s”,name);
}
output:
aeiou
main()
{
char name[20];
scanf(“%[a-z A-Z 0-9]”,name);
printf(“%s”,name);
}
output :
All combinations will be printing
main()
{
char name[20];
scanf(“%[^aeiou]”,name);
printf(“%s”,name);
}
main()
{
char ch;
printf(“print any key\n”);
scanf(“ %c”,&ch); (or) ch=getchar();
putch(ch);
}
printf:- The printf is used to print value on the screen in the given format.
44
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Syntax:- printf(“format_specifiers”,argument_list);
Integer mode output(%nd):- here ‘n’ indicates in how many digits places the given value
to be filled.
main()
{
Int a=123;
Printf(“%5d\n”,a);
Printf(“%4d\n”,a);
Printf(“%3d\n”,a);
Printf(“%2d\n”,a);
Printf(“%d\n”,a);
}
float mode output(%n.df):- here ‘n’ indicates in how many no.of digits to be printed after
the decimal point.
main()
{
Float pi=3.141592;
Printf(“%10.6f”,pi);
Printf(“%10.5f”,pi);
Printf(“%10.4f”,pi);
Printf(“%10.3f”,pi);
}
character mode output(%ns):- here ‘n’ indicates in how many digits places.
main()
{
Char name[10]=”rvrjc”;
Printf(“%8s”,name);
Printf(“%9s”,name);
Printf(“%10s”,name);
}
45
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
These selection control statements are used to execute the statements in the program
depending on a given particular condition.
(1) if (2) if else (3) nested if else (4) else if ladder (5) switch.
If:- This statements is used to execute a single statement or group of statements based
on a condition.
if the given expression is false, then the statements in the if block are not executed,
control goes to the next statement of the if expression.
Here expression can be any type which evaluates to either true (or) false.
#include<stdio.h>
main()
46
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
int age,
printf(“enter the age of the person\n”);
scanf(“%d”,&age);
if(age>=18)
printf(“ person is eligible to vote\n”);
}
if-else:- This if-else control statement is also known as two way decision control
structure.
Syntax:- if(expression)
{
statement 1;
statement 2;
……………
……………
statement n;
}
else
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
if the given expression is true, then the statements in the if block are executed and the
control goes to the first statement immediately below the else block.
if the given expression is false, then the statements in the if block are not executed, but
the statements in the else block are executed and the control goes to the next statement
after the else block.
Flow chart:-
47
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
If(expression1)
{
statement1;
statement2;
……………
statement n;
if(expression 2)
{
statement1;
statement2;
……………
statement n;
}
else
{
statement1;
statement2;
……………
statement n;
}
}
else
{
statement1;
statement2;
……………
statement n;
}
}
1) Write a program to find the maximum number from the given three numbers.
A)
main()
{
int a,b,c,max;
printf("enter the values for a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
if(a<b)
{
if(b<c)
max=c;
else
max=b;
}
else
{
if(a<c)
max=c;
48
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
else
max=a;
}
printf("the maximum number of %d %d %d is%d",a,b,c,max);
}
OUTPUT:
enter the values for a,b,c
4
9
5
the maximum number of 4 9 5 is 9.
else-if ladder:- the syntax of else-if ladder is
if(expression)
{
statement 1;
statement 2;
……………
……………
statement n;
}
else if(expression)
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
else if(expression)
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
…………………
…………………
else(expression)
{
statement 1;
statement 2;
…………….
…………….
statement n;
}
write a program to check whether the given character is in lower case or upper case
or digit or special character.
#include<stdio.h>
49
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
main()
{
int c;
printf("enter the character\n");
c=getchar();
if(c>='a' && c<='z')
printf("the given character is in lower case\n");
else if(c>='A' && c<='Z')
printf("the given character is in upper case\n");
else if(c>='0' && c<='9')
printf(" the given character is digit\n");
else
printf(" the given character is special character\n");
}
OUTPUT:
Write a program to read 3 subject marks of a student and find his average and print
the class he got according to his average.
Average class
Above 70 distinction..
60-69 First.
50-59 second.
35-49 third.
<=34 fail.
main()
{
int m1,m2,m3;
float avg;
printf("enter the 3 subjects marks of a student\n");
scanf("%d %d %d",&m1,&m2,&m3);
avg=(m1+m2+m3)/3.0;
printf("the average is %f\n",avg);
if(avg>=70)
50
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
OUTPUT:
51
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
SWITCH STATEMENT:
This switch control structure is used for making multi-way decision or multipath
decision.
Syntax:
switch(expression)
{
case value1: statement 1;
statement 2;
.
.
.
statement n;
break;
.
.
1. The switch control structure is having more readability than using if control
structures.
3. In the switch control structures if the given expression matches with value 1 then
the statements in that case are executed and control comes to the first
statement after the switch control structure due to the presence of break
statement.
4. If the given expression does not matches with value1 then it goes for checking
52
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Write a program to read a number and print its corresponding week day.
main()
{
int day;
printf(“Enter number of week day:\n”);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“MONDAY”);
break;
case 2: printf(“TUESDAY”);
break;
case 3: printf(“WEDNESDAY”);
break;
case 4: printf(“THURSDAY”);
break;
case 5: printf(“FRIDAY”);
break;
case 6: printf(“SATURDAY”);
break;
case 7: printf(“SUNDAY”);
break;
default: printf(“Invalid Week day\n”);
Ourput:
Write a program to read a number and print its corresponding month name
main()
{
53
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
int day;
printf(“Enter number of the month:\n”);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“JANUARY”);
break;
case 2: printf(“FEBRUARY”);
break;
case 3: printf(“MARCH”);
break;
case 4: printf(“APRIL”);
break;
case 5: printf(“MAY”);
break;
case 6: printf(“JUNE”);
break;
case 7: printf(“JULY”);
break;
case 8: printf(“AUGUST”);
break;
case 9: printf(“SEPTEMBER”);
break;
case 10: printf(“OCTOBER”);
break;
case 11: printf(“NOVEMBER”);
break;
case 12: printf(“DECEMBER”);
break;
output:
Enter number of the month:
5
MAY
main()
54
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
int a,b;
char operator;
printf(“Enter 2 numbers\n”);
scanf(“%d%d”,&a,&b);
printf(“Enter your choice\n”);
printf(“ + Addition \t – Subtration \t *Multiplication \t / division \t %Modulo \n”);
scanf(“%c”,&operator);
switch(operator)
{
case ‘+’:printf(“%d + %d =%d\n”,a,b,a+b);
break;
case ‘-’:printf(“%d - %d =%d\n”,a,b,a-b);
break;
case ‘*’:printf(“%d * %d =%d\n”,a,b,a*b);
break;
case ‘/’:printf(“%d / %d =%d\n”,a,b,a/b);
break;
case ‘%’:printf(“%d % %d =%d\n”,a,b,a%b);
break;
default: printf(“enter invalid operator\n”);
}
}
Output:
Enter 2 numbers
10 20
+
10+20=30
flow chart for switch case:-
Eg: main()
{
int n=3;
switch(n)
{
case 4: printf(“Four”);
break;
case 3: printf(“three”);
break;
case 2: printf(“two”);
break;
default: printf(“Four”);
break;
55
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
}
}
Eg: main()
{
char ch;
printf(“Enter a character”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
case ‘A’:
case ‘e’:
case ‘E’:
case ‘i’:
case ‘I’:
case ‘o’:
case ‘O’:
case ‘u’:
case ‘U’:printf(“The Given character is vowel”);
break;
default: printf(“The character is constant\n”);
}
}
output:
Enter a character
A
The Given character is vowel
5. In switch statement these can be some cases having integer type arguments,
there can be some cases having char type.
6. In switch statement if a statement is present, then it must belong to some
particular case is the switch otherwise that statement is not executed forever.
Eg; main()
{
int n=1;
switch(n)
{
56
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf(“Good Morning”);
case 1:printf(“One\n”);
case 2:printf(“Two\n”);
default: printf(“Hello”);
}
}
7. In switch statement we should not write conditions in the cases. But we can write
conditions in the expression.
8. In switch statement unlike if control structure the entire statements is a
particular case are not written in cur lee braces.
9. Using switch case, we can write more structured programs than using if
statement.
1) Write a program to find whether the given no is +ve or –ve and the given no is even or
odd.
main()
{
int n,ch;
printf(“Enter the value of n”);
scanf(“%d”,&n);
printf(“Enter your choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: if(n>=0)
printf(“%d is positive”,n);
else
printf(“%d is negative”,n);
break;
case 2: if(n%2==0)
printf(“%d is EVEN”,n);
else
printf(“%d is ODD”,n);
break;
default: printf(“No condition is satisfied”);
}
}
output:
Enter the value of n
6
Enter your choice
1
6 is positive
57
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
char ch;
printf("enter a character \n");
scanf(" %c",&ch);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("%c is vowel",ch);
else
printf("%c is not vowel",ch);
}
OUTPUT:
enter a character
s
s is not vowel
enter a character
i
i is vowel
OUTPUT:
enter a character
k
k is alpha numeric
enter a character
9
9 is alpha numeric
enter a character
?
? is not alpha numeric
rd
4) Write a program to swap the contents of two variables without using 3 variable.
A) main()
{
int a,b;
printf("enter the two numbers\n");
58
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
scanf("%d %d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("after swaping a=%d b=%d",a,b);
}
OUTPUT:
enter the two numbers
5
4
after swaping a=4 b=5
5) Write a program to convert the given character in to lower case.
A) main()
{
char ch;
printf(" enter a character\n");
scanf(" %c",&ch);
if(ch>=65&&ch<=90)
{
ch=ch+32;
printf("the given character in lower case %c",ch);
}
else
printf(" %c is not a upper case",ch);
}
OUTPUT:
enter a character
s
s is not a upper case
enter a character
S
s
6) write a program to convert the character in to upper case.
A) main()
{
char ch;
printf(" enter a character\n");
scanf(" %c",&ch);
if(ch>=97&&ch<=122)
{
ch=ch-32;
printf("the given character in upper case %c",ch);
}
else
printf(" %c is not lower case",ch);
}
Iterative control structures (or) Repetitive structures:
while
do-while
for
59
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
These structures are used to repeatedly execute a particular statements (or) group of
statements based on a given condition.
The statements in the while loop are executed till the expression is true. When
expression in the while loop is false, then control goes to first statement immediately
below the while loop.
Flow chart:-
60
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf("enter a number\n");
scanf("%d",&n);
while(i<=n)
{
fact=fact*i;
i++;
}
printf("factorial of %d is %d",n,fact);
}
OUTPUT:-
enter a number
5
factorial of 5 is 120
enter a number
9
factorial of 9 is 362880.
#include<stdio.h>
main()
{
int n,i;
printf("enter the number\n");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf("%3d x %3d = %3d\n",n,i,n*i);
i++;
}
}
OUTPUT:-
enter the number
9
9x 1= 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
Do-while: - Exit controlled loop (or) post condition testing loop
The do-while loop performs the test at the bottom rather than at the top.
The do-while loop starts with the keyworddo, followed by the body of the loop.
61
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Syntax:do
{
Statement 1;
Statement 2;
……………..
Statement n;
}while(expression);
After executing the body of the loop it reaches while, the expression specified is
evaluated. If it is found to be true, automatically loop back to the top and re-enter the
body of the loop.
At the time of testing, the condition evaluates as false, then the control breakout
the do-while loop.
Print hello 10 times using do-while.
main()
{
Int I;
do
{
printf(“hello\n”);
i++;
}while(i<<=10);
}
1) The while loop is called precondition testing loop because the condition is
checked initially before the statements are executed. Do-while loop is called past
condition testing loop that means condition is checked once the statements are
62
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
executed.
2) In the while loop, there is no semicolon at end of condition, but in do-while there
must be semicolon at end of condition.
3) In the while loop, the statements may executed or may not be executed
depending on conditions. But in do-while the statements are executed at least
one type whether the given condition is true/false.
Ex:
main() main()
{ {
While(4<1) do
{ {
printf(“hello\n”); printf(“hello\n”);
} }while(4<1);
} }
#include<stdio.h>
main()
{
int n,a,sum=0;
printf("enter a number\n");
scanf("%d",&n);
a=n%10;
sum=sum+a;
n=n/10;
sum=sum+n;
printf("sum=%d",sum);
}
OUTPUT:
enter a number
31
sum=4
63
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf("sum=%d",sum);
}
OUTPUT:
enter a number
143
sum=8.
For loop:- This is used when the statements are to be executed more than once. This is
the most widely used iteration construct.
in the for loop the initialization section is executed afterwards the given condition is
checked. If the given condition is true, the statements in the for loop are executed and
the control comes to increment/decrement section and then the goes to conditional part.
Note: the initialization part is executed only for the first time only.
Flow chart:-
64
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
scanf("%d",&n);
for(i=1;i<=n;i++)
fact=fact*i;
printf("the factorial of %d is %d",n,fact);
}
OUTPUT:
enter the number
6
the factorial of 6 is 720.
write a program to display multiplication table for given number.
#include<stdio.h>
main()
{
int n,i;
printf("enter the number\n");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d x %3d = %3d\n",n,i,n*i);
}
OUTPUT:
enter the number
5
5x 1= 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Write a program to print 1 to n natural numbers.
main()
{
int I,n;
printf(“enter a number\n”);
scanf(“%d”,&n);
i=1;
while(i<=n) do for(;i<=n;i++)
{ { {
printf(“%d”,i); printf(“%d”,i); printf(“%d”,i);
i++; i++; }
} }
}
Write a program to print n to 1 natural numbers.
main()
{
int I,n;
65
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf(“enter a number\n”);
scanf(“%d”,&n);
while(n>=1) do for(;n>=1;n--)
{ { {
printf(“%d”,n); printf(“%d”,n); printf(“%d”,n);
n--; n--; }
} }while(n>=1);
}
Write a program to find sum of digits of a given number by using loops.
main()
{
int n,a,sum=0;
printf(“enter a number\n”);
scanf(“%d”,&n);
while(n>0) do for(;n>0;n=n/10)
{ { {
a=n%10; a=n%10; a=n%10;
sum=sum+a; sum=sum+a; sum=sum+a;
n=n/10; n=n/10; }
} }while(n>0);
printf(“ sum=%d”,sum);
}
write a program to find reverse (or) image of a given number by using loops.
main()
{
int n,a,m,rev=0;
printf(“enter a number\n”);
scanf(“%d”,&n);
m=n;
while(n>0) do for(m=n;n>0;n=n/10)
{ { {
a=n%10; a=n%10; a=n%10;
rev=rev*10+a; rev=rev*10+a; rev=rev*10+a;
n=n/10; n=n/10; }
} }while(n>0);
66
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
#include<stdio.h>
main()
{
int a=0,b=1,c,n;
printf("enter the number\n");
scanf("%d",&n);
printf("%d %d",a,b);
c=a+b;
while(c<=n)
{
printf("\t%d",c);
a=b;
b=c;
c=a+b;
OUTPUT:
enter a number
153
sum=153
67
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
enter a number
345
sum=216
the given number is not Armstrong number
#include<stdio.h>
main()
{
int n,i=2,c=0;
printf("enter the number\n");
scanf("%d",&n);
while(i<n) for(i=2;i<n;i++)
{ {
if(n%i==0) if(n%i==0)
c++; c++;
i++; }
}
if(c==0)
printf("%d is prime",n);
else
printf("%d is not prime",n);
}
OUTPUT:
#include<stdio.h>
main()
{
char name[20];
printf("enter the multiple lines\n");
scanf("%[^\t]",name);
}
Type modifiers:
The type modifiers are used to change or to alter the basic meaning of the given
data type. The type modifiers are used to redirect the given data type to take only
specified range of value.
The following are the different type modifiers.
68
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Signed
Unsigned
Short
Long
All these can be applied to int.
signed
unsigned signed
int long char unsigned
short
float -- long
double -- long
69
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
scanf("%d",&n);
while(i<=n)
{
j=1;
while(j<=n)
{
printf("\t*");
j++;
}
printf("\n");
i++;
}
}
OUTPUT:
enter the number
2
* *
* *
enter the number
3
* * *
* * *
* * *
To find whether the number is perfect (or) deficient (or) abundant no
main()
{
int i,n,sum=0;
printf("enter the number\n");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
sum=sum+i;
}
if(sum==n)
printf("%d is perfect number\n",n);
else if(sum<n)
printf("%d is deficient number\n",n);
else
printf("%d is abundant number\n",n);
}
OUTPUT:
enter the number
6
6 is perfect number
70
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
71
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Break : This break statement terminates the execution of the loop and the control is
transferred to the statement immediately following the loop.
Syntax: break;
Infinite loops:-
} }while(11);
Arrays
An array is a collection of elements of similar type, those sharing a common name and
occupies contiguous locations.
72
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
DECLARATION OF ARRAYS
Array may be of one dimensional or multi dimensional. Declarations of the one
dimensional arrays, two dimensional arrays and three dimensional arrays are as follows.
Here data_type refers to the data type of the elements in the array and it can be a
primitive data type. arrayname1, arrayname2…..etc refers to the identifiers which
represent the array name. Size is an integer expression representing total number of
elements in the array.
Example
int Num[10];
It is the declaration of a one dimensional array which defines an integer array name Num
of size 10 and that represents a block of 10 consecutive storage locations. Here each
element in the array is represented by Num[0], Num[1],….,Num[9], where 0, 1, 2, …, 9
represents subscripts or indices of the array.
In general Num [ i ] refers to the ith element of the array. The representation of
one dimensional array in memory is as follows.
Num[0] Num[1] Num[2] Num[3] Num[4] Num[5] Num[6] Num[7] Num[8] Num[9]
1024 1026 1028 1030 1032 1034 1036 1038 1040 1042
Addresses
Let us consider the above example Num it self represent the base address of the
entire array. &Num [0] also represents the base address. &Num [5] represents the
th
address of the 6 element in the array Num, and it is calculated using the formulae
th
Address of the i element = base address + i * scale factor
73
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
The scale factor is the number of byes allocated for each element of the array.
The address of array Num [5] is calculated as
&Num [5] = 1024 + 5 * 2 = 1034.
Here &Num [5] is also represented as (num+5).
Here data_type refers to the data type of the elements in the array and it can be a
primitive data type. array_name refers to the identifiers which represent the array name.
Size1 is an integer expression representing the row size in the array and Size2 is also an
integer expression representing the column size in the array. In a two dimensional array
two subscripts are used in two pairs of square brackets.
Example
int Num[2][2];
It is the declaration of a two dimensional array which defines an integer array name Num
of row size 2 with column size 2 and that represents a block of 4 consecutive storage
locations. Here each element in the array is represented by Num[0][0],
Num[0][1],Num[1][0] and num[1][1].
th th
In general Num[ i ][ j ] refers to the element of the i row and j column in the
array. The representation of a two dimensional array in the memory is as follows.
Let us consider the above example Num it self represent the base address of the
entire array. &Num [0][0] also represents the base address. &Num [1][0] represents the
address of the 2nd row 1st column element in that array Num, and it is calculated using
the formulae
Address of the [ i, j]th element = base address + i * total no of columns * scale factor + j * scale factor
The scale factor is the number of byes allocated for each element of the array.
The address of array Num [1][1] is calculated as
&Num [1][1] = 1024 + 1 * 2 *2 + 1*2= 1030.
Write a program to read a two dimensional array and print that array.
#include<stdio.h>
main( )
{
int a[10][10], i, j, m, n ;
printf (“ Enter the number of rows and columns: “);
scanf (“ %d %d“, &m, &n );
for( i=0; i<m; i++ )
{
for( j=0; j<n; j++ )
{
printf ( “ Enter the value of a[%d][%d] : “ , i, j );
scanf (“ %d “, &a[ i ][ j ]);
}
}
printf (“ The array elements are ; “);
for( i=0; i<m; i++ )
for( j=0; j<n; j++)
printf (“ \t %d “, a[ i ][ j ]);
}
In the three dimensional array 3 subscripts are placed as three pairs of square brackets,
Where as size1 represents the number of pages, size2 represents the number of rows
and size3 represents the number of columns. The total number of elements in a three
dimensional array is calculated as No of pages * No of rows * No of columns.
Example
int a[2][2][2];
The value in the kth page, ith row and jth column is referred to by a[ k ][ i ][ j ]. The memory
representation of a three dimensional array is as follows.
Write a program to read p pages, m rows and n columns of elements and print them.
#include<stdio.h>
main()
{
int a[3][3][3], i, j, k, p, m, n;
printf ( “ Enter how many page numbers, rows and columns you want\n “);
scanf ( “ %d %d %d “, &p, &m, &n);
for( k=0; k<p; k++)
{
for( i=0; i<m; i++)
{
for( j=0; j<n; j++)
{
printf ( “ Enter element for a[%d][%d][%d] : “,k, i, j);
scanf ( “ %d “, &a[ k ][ i ][ j ]);
}
}
}
76
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
INITIALISATION OF ARRAYS
The elements of an array may be assigned with the values using initialization
instead of reading them by the I/O functions. An array can be initialized in its declaration
only. The lists of values are enclosed in braces. The values are separated by commas
and they must be constants or constant expressions.
If the number of values initialised for an array is less than the size mentioned, the
missing elements are assigned to zero.
Example
int a[3][4]={ {1,2},{3,4,5} };
In the above example the elements a[0][0], a[0][1] of the 0th row and a[1][0], a[1][1]
and a[1][2] of the 1st row are initialised with the values 1,2,3,4 and 5 respectively. All the
other elements are initialised to zero. If the number of initial values exceeds the size of
the array, it is an error.
Example
int a[3][4]={1,2,3,4,5};
In the above example the values are assigned from left end to a[0][0], a[0][1],
a[0][2], a[0][3] and a[1][0] according to the order of the storage representation.
The size of a one dimensional array need not be mentioned in its initialization. In
this case, the compiler will count the values assigned and take it as the size of that array.
In multi dimensional arrays the leftmost subscript may be omitted and all others must
be specified.
Example
int x[ ]={1,2,3,4,5};
The initialization makes the array x having 5 elements
Example
int a[ ][2]={1,2,3,4};
The initialization makes the array a having 2 rows and 2 columns.
77
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Example
float x[ ][3]={{1},{2},{3}};
The declaration represents a three by three array with only the first element in each row
is initialised.
Example
float x[ ][3]={ {1,2,3} };
The above declaration represents a one by three array. Hence, the internal braces are
important in fixing the size of the dimension when leftmost dimension is omitted. The
missing elements of a initialised array are assigned the value zero.
write a program to find maximum and minimum elements in the given array.
#include<stdio.h>
main()
{
int a[20],i, n, max, min;
printf ( "Enter value of n : ");
scanf ( "%d" , &n);
for( i=0; i<n; i++)
{
printf ( "Enter element for a[%d] : ",i );
scanf ( "%d", &a[ i ]);
}
max=min=a[0];
for( i=1; i<n; i++)
{
if(max < a[ i ])
max=a[ i ];
if(min > a[ i ])
min=a[ i ];
}
printf ( "Maximum element =%d\n Minimum element=%d\n", max, min);
}
OUTPUT:
Enter value of n : 5
Enter element for a[0] : 2
Enter element for a[1] : 5
Enter element for a[2] : 6
Enter element for a[3] : 3
78
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Write a program to find no.of +ve and –ve elements in the given array.
main()
{
int a[10],p=0,n=0,i,x;
printf("enter the size of the array \n");
scanf("%d",&x);
printf("enter the elements in the array\n");
for(i=0;i<x;i++)
scanf("%d",&a[i]);
for(i=0;i<x;i++)
{
if(a[i]>0)
p++;
else
n++;
}
printf("no.of +ve numbers are %d",p);
printf("no of -ve numbers are %d",n);
}
OUTPUT:
enter the size of the array
5
enter the elements in the array
2
-8
5
-9
1
no.of +ve numbers are 3no of -ve numbers are 2
79
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\nenter the serching element\n");
scanf("%d",&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
c++;
}
if(c>0)
printf("the element is found and %d times occurred\n",c);
else
printf("the element is not found\n");
}
OUTPUT:
main()
{
int a[10],b[10],n,i;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements in A are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
b[i]=a[i];
printf("\n the array elements in B are\n");
80
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
for(i=0;i<n;i++)
{
printf("%d\t",b[i]);
}
}
OUTPUT:
main()
{
int a[10],n,i;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements in A are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n the reverse elements in A are\n");
for(i=n-1;i>=0;i--)
{
printf("%d\t",a[i]);
}
}
OUTPUT:
81
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
3
4
5
the array elements in A are
1 2 3 4 5
the reverse elements in A are
5 4 3 2 1
main()
{
int a[10],n,i,size;
printf("enter the number\n");
scanf("%d",&n);
i=0;
while(n>0)
{
a[i]=n%10;
n=n/10;
i++;
}
size=i;
for(i=size-1;i>=0;i--)
{
switch(a[i])
{
case 0:printf("zero\t");break;
case 1:printf("one\t");break;
case 2:printf("two\t");break;
case 3:printf("three\t");break;
case 4:printf("four\t");break;
case 5:printf("five\t");break;
case 6:printf("six\t");break;
case 7:printf("seven\t");break;
case 8:printf("eight\t");break;
case 9:printf("nine\t");break;
}
}
}
OUTPUT:
enter the number
2345
two three four five
write a program to find the binary equivalent of the given number
main()
{
int a[10],n,i,size;
printf("enter the number\n");
scanf("%d",&n);
82
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
i=0;
while(n>0)
{
a[i]=n%2;
n=n/2;
i++;
}
size=i;
for(i=size-1;i>=0;i--)
{
printf("%d\t",a[i]);
}
}
OUTPUT:
enter the number
12
1 1 0 0
OUTPUT:
enter the size of the array
5
enter the elements in to the array
1
2
3
4
5
the array elements are
83
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
1 2 3 4 5
enter the positions to be reversed
3
4
1 2 4 3 5
Write a program to replace an element in the array with the given element.
main()
{
int a[10],n,i,old,new,c=0;
printf("enter the size of the array\n");
scanf("%d",&n);
printf("enter the elements in to the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\nenter the element to be replaced\n");
scanf("%d",&old);
printf("enter the replacing elment\n");
scanf("%d",&new);
for(i=0;i<n;i++)
{
if(a[i]==old)
{
a[i]=new;
c++;
}
}
if(c==0)
printf("the element is not found\n");
else
{
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
}
OUTPUT:
enter the size of the array
5
enter the elements in to the array
1
2
3
4
5
the array elements are
1 2 3 4 5
enter the element to be replaced
4
84
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
85
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
4
5
the sum of the array elements is 15
Write a program to find sum of even no’s of sum of odd no’s in the given array.
#include<stdio.h>
main()
{
int a[10],i,n,evensum=0,oddsum=0;
printf("enter the array size\n");
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d",a[i]);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
evensum=evensum+a[i];
else
oddsum=oddsum+a[i];
}
printf("the sum of the even numbers are %d\n",evensum);
printf("the sum of odd numbers are %d\n",oddsum);
}
OUTPUT:
enter the array size
5
enter the array elements
1
2
3
4
5
the array elements are
12345
the sum of the even numbers are 6
the sum of odd numbers are 9
Write a program to read elements from the keyboard and display the even number
array and odd number array separately.
#include<stdio.h>
main()
{
int a[10],i,n,e[10],o[10],oi=0,ei=0;
printf("enter the array size\n");
86
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
scanf("%d",&n);
printf("enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
e[++ei]=a[i];
else
o[++oi]=a[i];
}
printf("\nthe even numbers array is\n");
for(i=1;i<=ei;i++)
printf("%d\t",e[i]);
OUTPUT:
enter the array size
6
enter the array elements
1
2
3
4
5
6
the array elements are
1 2 3 4 5 6
the even numbers array is
2 4 6
the odd numbers array is
1 3 5
87
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf("%d\t",a[i]);
}
OUTPUT:
0 1 1 2 3 5 8 13 21 34
if(a[i]!=x)
printf("%d elememt is not found\n",x);
else
printf("%d element is found\n",x);
}
OUTPUT:
enter a number
9
enter the array elements
1
2
3
4
5
5
6
7
8
9
the array elements are
1 2 3 4 5 5 6 7 8 9
9 element is found
/* A menu driven program to display statistical parameters
using one-dimensional arrays
i) Mean ii) Medain iii) Mode iv) Variance v)Standard deviation*/
#include<math.h>
#define maxsize 10
88
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
main()
{
int n,a[maxsize],ch,i,j,t,flag,it,y;
float mean,mode,median,var,sd,sum;
printf("enter howmany numbers do u want to give\n");
scanf("%d",&n);
printf("enter the elements in the array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the elements in the array are\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
do
{
printf(" 1.mean\n 2.median\n 3.mode\n 4.varience\n 5.standard deviation\n
6.exit \n");
printf("enter your option\n");
scanf("%d",&ch);
switch(ch)
{
case 1: sum=0;
for(i=0;i<n;i++)
sum=sum+a[i];
mean=sum/n;
printf("the mean of the given numbers is %f\n",mean);
break;
case 2: for(it=0;it<n-1;it++)
{
for(j=0;j<n-1;j++)
{
if(a[j]<a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
if(n%2!=0)
median=a[n/2];
else
median=(a[n/2]+a[(n/2)-1])/2.0;
printf("the median is %f %d %d\n",median,a[n/2],a[n/2-1]);
break;
case 3: mode=((3*median)-(2*mean));
printf("the mode is %f\n",mode);
break;
case 4: sum=0;
for(i=0;i<n;i++)
89
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
y=(a[i]-mean)*(a[i]-mean);
sum=sum+y;
}
var=sum/n;
printf("the varience is %f\n",var);
break;
case 5: sd=sqrt(var);
printf("the standard deviation is %f\n",sd);
break;
case 6: exit();
break;
default : printf("invalid option\n");
break;
}
}while(ch<=6);
}
main()
{
int choice;
while(1)
{
printf("\n1.read\n2.display\n3.reverse\n4.insert\n5.delete\n6.remove\n");
printf("7.exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:read(); break;
case 2:display(); break;
case 3:reverse(); break;
case 4:insert(); break;
case 5:delete(); break;
case 6:rem(); break;
case 7:exit(); break;
90
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
}
}
}
void read()
{
int i;
printf("Enter a number:");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display()
{
int i;
printf("The array elements are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void reverse()
{
int i,j,temp;
for(i=0,j=n-1;i<j;i++,j--)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
display();
}
void insert()
{
int i,pos,ele;
printf("Enter the position to insert:");
scanf("%d",&pos);
if(pos<1 ||pos>n)
{
printf("\nNot valid position:");
return;
}
printf("\nEnter the element to be insert:");
scanf("%d",&ele);
for(n++,i=n-1;i>pos-1;i--)
{
a[i]=a[i-1];
}
a[pos-1]=ele;
display();
}
91
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
void delete()
{
int i,pos,ele,c=0;
printf("Enter element to delete:");
scanf("%d",&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
for(pos=i;pos<n-1;pos++)
a[pos]=a[pos+1];
n--;
i--;
c=1;
}
}
if(c==0)
{
printf("The element is not found in the array:\n");
}
display();
}
void rem()
{
int i,j,pos,c=0;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
for(pos=j;pos<n-1;pos++)
a[pos]=a[pos+1];
n--;
j--;
c=1;
}
}
if(c==0)
{
printf("The duplicate element is not :\n");
}
display();
}
Arrays in functions:-
Function prototype
92
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Function call:-
Functionname (arrayname, size);
Function definition:-
returntype functionname((data type arrayname[size],data type number)
{
statement 1;
statement 2;
…………….
…………….
Statement n;
}
Write a program to read and print array elements.
void read(int a[],int n);
void display(int [],int);
main()
{
int a[10],n;
printf("enter the no of elements\n");
scanf("%d",&n);
read(a,n);
display(a,n);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
OUTPUT:-
enter the no of elements
5
enter the array elemnets
2
4
1
3
5
the array elements are
2 4 1 3 5
93
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
The default mechanism in which the variables are passed to function is call by value.
The default mechanism in which the array is passed to function is call by reference.
Write a program to insert an element into the array.
void read(int a[],int n);
void display(int [],int);
int insert(int[],int,int,int);
main()
{
int a[10],n,pos,ele;
printf("enter the no of elements\n");
scanf("%d",&n);
read(a,n);
printf("before element insertion\n");
display(a,n);
printf("enter the element to insert\n");
scanf("%d",&ele);
printf("enter the position that the element to be insert\n");
scanf("%d",&pos);
n=insert(a,n,pos,ele);
printf("after element insertion\n");
display(a,n);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
int insert(int a[10],int n,int pos,int ele)
{
int i;
if(pos<1||pos>n)
{
printf("insertion is not possible\n");
return;
}
else
{
for(n++,i=n-1;i>pos-1;i--)
a[i]=a[i-1];
a[pos-1]=ele;
}
94
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
return n;
}
OUTPUT:
enter the no of elements
5
enter the array elemnets
1
2
3
4
5
before element insertion
the array elements are
1 2 3 4 5
enter the element to insert
9
enter the position that the element to be insert
3
after element insertion
the array elements are
1 2 9 3 4 5
Write a program to copy one array elements into another by using functions.
95
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void copyarray(int a[10],int b[10],int n)
{
int i;
for(i=0;i<n;i++)
b[i]=a[i];
}
OUTPUT:
enter the no of elements
5
enter the array elemnets
1
2
3
4
5
the first array elements are
1 2 3 4 5
the second array elements are
1 2 3 4 5
Write a program to copy two array elements into third array.
void read(int a[],int n);
void display(int [],int);
void copy(int [],int,int [],int,int []);
main()
{
int a[10],b[10],c[20],m,n,p;
printf("enter the no of elments in A array\n");
scanf("%d",&m);
printf("enter the no of elements in B array\n");
scanf("%d",&n);
p=m+n;
printf("enter A elements\n");
read(a,m);
printf("emter B elements\n");
read(b,n);
copy(a,m,b,n,c);
printf("A elements are\n");
display(a,m);
printf("B elements are\n");
display(b,n);
printf("C elements are\n");
display(c,p);
}
void read(int a[10],int n)
{
int i;
printf("enter the array elemnets\n");
for(i=0;i<n;i++)
96
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
scanf("%d",&a[i]);
}
void display(int a[10],int n)
{
int i;
printf("the array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void copy(int a[10],int m,int b[10],int n,int c[20])
{
int i,j=0;
for(i=0;i<m;i++)
{
c[j]=a[i];
j++;
}
for(i=0;i<n;i++)
{
c[j]=b[i];
j++;
}
}
OUTPUT:
enter the no of elments in A array
3
enter the no of elements in B array
3
enter A elements
enter the array elemnets
1
2
3
emter B elemets
enter the array elemnets
4
5
6
the A array elements are
1 2 3
the B array elements are
4 5 6
the C array elements are
1 2 3 4 5 6
Write a function that takes 3 arguments array,no.of elements, searching element and
it returns 1 if the searching element is found other wise it returns 0.
Int search(int a[],int n,int x)
{
int I;
for(i=0;i<n;i++)
{
97
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
if(a[i]==x)
return 1;
}
return 0’
}
ex:-
int a[2][2]; col 0 col 1
A[0][0] 100 A[0][1] 102
B[0][0] 104 B[0][1] 106
Float b[2][3]
Col 0 col 2 col 3
B[0][0] B[0][1] B[0][2]
B[1][0] B[1][1] B[1][2]
Initialization of DDA:-
1) compile time initialization
2) runtime initialization.
98
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
Note: when a DDA is initialized at the time of its declaration then, specification of row
size is optional, but column size must be compulsorily specified why because depending
upon the no. of columns, the computer assumes the no. of rows.
main()
{
int a[5][5],i,j,m,n;
printf("enter number rows and columns\n");
scanf("%d %d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("enter a[%d][%d] element\n",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("the DDA elements are\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
}
OUTPUT:
enter number rows and columns
2
3
enter a[1][1] element
1
enter a[1][2] element
3
enter a[1][3] element
5
enter a[2][1] element
2
enter a[2][2] element
4
enter a[2][3] element
6
the DDA elements are
1 3 5 2 4 6
Write a program to find no. of even no’s & no. of odd no’s in the given matrix and also
99
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
OUTPUT:
enter number rows and columns
2
3
enter a[1][1] element
1
enter a[1][2] element
2
enter a[1][3] element
3
enter a[2][1] element
4
enter a[2][2] element
5
enter a[2][3] element
6
the DDA elements are
1 2 3 4 5 6
the biggest element is = 6
the biggest elementlocation is a[2][3]=6
the smallest elment is=1
the smallest elmentlocation is a[1][1]=1
function _name(arrayname,rowsize,columnsize);
function definition(called function)
returntype function_name(datatype var[ row ][ col ],int m,int n);
function prototype:-
returntype function_name(datatype var[ row ][ col ],int m,int n);
(or)
returntype function_name(datatype var[ ][ col ],int m,int n);
(or)
returntype function_name(datatype [ ][ col ],int ,int );
(or)
returntype function_name(datatype [ row ][ col ],int ,int );
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
}
void read(int b[][5],int m,int n)
{
int i,j;
printf("enter matrix elememts\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
}
main()
{
int a[5][5],m,n;
printf("enter the size of the matrix\n");
scanf("%d %d",&m,&n);
read(a,m,n);
display(a,m,n);
diagonal(a,m,n);
}
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
OUTPUT:
enter the size of the matrix
2
2
enter matrix elememts
1
2
3
4
the matrx elements are
1 2 3 4
sum=5
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(i==j)
a[i][j]=1;
else
a[i][j]=0;
}
else
printf("\ngiven matrix is not square matrix\n");
}
OUTPUT:
enter the size of the matrix
2
2
enter matrix elememts
1
2
3
4
before unit matrix
the matrx elements are
1 2 3 4
after unit matrix
the matrx elements are
1 0 0 1
Write to interchange the given two row elements in a matrix.
Void interchange(int a[][5],int m,int n)
{
int I,j,r1,r2,temp;
printf(“enter the rows to be interchanged\n”);
scanf(“%d %d”,&r1.&r2);
if(r1<1 || r1>m || r2<1 || r2>n)
{
printf(“invalid row numbers\n”);
return;
}
for(j=0;j<n;j++)
{
temp = a[r1 -1][ j ];
a[r1 -1][ j ] = a[r2 -1][ j ];
a[r2 -1][ j ] =temp;
}
}
Write to transpose a given matrix.
Void tranpose(int a[][5],int m,int n)
{
int b[5][5],I,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
b[ j ][ I ]= a [ I ] [ j ];
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
#include<stdio.h>
void read(int [][],int,int);
void display(int [][],int,int);
void add(int [][],int,int,int [][],int,int);
void mul(int [][],int [][],int ,int,int);
void trans(int [][],int,int);
void check(int [][],int [][],int,int);
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
main()
{
int a[5][5],b[5][5],m,n,p,q,i,j,choice;
do
{
printf("\n1.Read\n2.A+B\n3.AxB\n4.Transpose\n5.Check A=B\n6.exit");
printf("Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:printf(" Enter the A matrix size:");
scanf("%d%d",&m,&n);
printf("Enter A matrix elements:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
10
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
}
printf("\n");
}
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
FUNCTIONS
Functions
Advantages of functions:-
1) Code of the program is reduced.
2) Time saved.
3) Memory consumption is also reduced.
4) Readability of program also increases.
5) Error checking is minimized.
main()
{
printf(“main function\n”);
one();
two();
three();
}
void one()
{
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
printf(“one\n”);
}
void two()
{
printf(“two\n”);
}
void three()
{
printf(“three\n”);
}
Code reusability:-
void line();
main()
{
printf(“ countries\n”);
line();
printf(“India \t usa \n”) ;
line();
printf(“new delhi \t washington \n”);
}
void line()
{
int I;
for(i=1;i<=10;i++)
printf(“-------------“);
}
Function prototype:- It defines a template which instructs the compiler about the details
of function, such as the name of the function, the no.of arguments the function is taking
and the type of arguments and the type of value returned by the function.
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
void fact();
main()
{
fact();
}
void fact()
{
int n,fact=1,m;
printf("enter the number\n");
scanf("%d",&n);
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}
OUTPUT:
void prime();
main()
{
prime();
}
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
void prime()
{
int n,i=2,c=0;
printf("enter the number\n");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
c++;
}
if(c==0)
printf("%d is prime",n);
else
printf("%d is not prime",n);
}
OUTPUT:
enter the number
7
7 is prime
enter the number
4
4 is not prime
II type
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
{
if(n%2==0)
printf(“%d is even”,n);
else
printf(“%d is odd”,n);
}
III type
void factorial(int n,int fact,int m);
main()
{
int n,fact=1,m;
printf("enter a number\n");
scanf("%d",&n);
factorial(n,fact,m);
}
void factorial(int n,int fact,int m)
{
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}
OUTPUT:
enter a number
5
factorial of 5 is 120
III type
void prime(int n,int i,int c);
main()
{
int n,i=2,c=0;
printf("enter the number\n");
scanf("%d",&n);
prime(n,i,c);
}
void prime(int n,int i,int c)
{
for(i=2;i<n;i++)
{
if(n%i==0)
c++;
}
if(c==0)
printf("%d is prime",n);
else
printf("%d is not prime",n);
}
OUTPUT:
enter the number
7
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
7 is prime
enter the number
4
4 is not prime
IV type :
void avg();
main()
{
avg();
}
void avg()
{
int a,b,c;
float avg;
printf("enter the values of a,b,c\n");
scanf("%d %d %d",&a,&b,&c);
avg=(a+b+c)/3.0;
printf("average is %f",avg);
}
OUTPUT:
II type :
void average(int a,int b,int c,float avg);
main()
{
int a,b,c;
float avg;
printf("enter the values of a,b,c\n");
scanf("%d %d %d",&a,&b,&c);
average(a,b,c,avg);
}
void average(int a,int b,int c,float avg)
{
avg=(a+b+c)/3.0;
printf("average is %f",avg);
}
OUTPUT:
enter the values of a,b,c
2
6
11
‘C’ programming R.V.R. & J.C. COLLEGE OF ENGINEERING
5
average is 4.333333
I – TYPE II - TYPE
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
I – Type : In this case the functions doesn’t contain any arguments as well as the no return
values.
II – Type : In this case the functions will accept the arguments and doesn’t contains any return
values.
III – Type : In this case the functions will accept the arguments and it contains the return values.
I – TYPE
void factorial();
main()
{
factorial();
}
void factorial()
{
int n,fact=1,m;
printf("enter a number\n");
scanf("%d",&n);
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}
OUTPUT:
enter a number
6
factorial of 6 is 720
II - TYPE
void factorial(int n,int fact,int m);
main()
{
int n,fact=1,m;
printf("enter a number\n");
scanf("%d",&n);
factorial(n,fact,m);
}
void factorial(int n,int fact,int m)
{
for(m=n;n>0;fact=fact*n,n--)
{
}
printf("factorial of %d is %d",m,fact);
}
OUTPUT:
enter a number
4
factorial of 4 is 24.
Global variable:- It is a variable which is declared outside of all the functions in the program.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Once a variable is declared as global, it’s life time is present during the entire program.
A global variable is known to every function in the program and it’s value can be
accessed, modified by any function.
int x;
void one();
void two();
main()
{
x=10;
printf(“ x in main=%d”,x);
one();
two();
}
void one()
{
x=20;
printf(“ x in one=%d”,x);
}
void two()
{
x=30;
printf(“ x in two=%d”,x);
}
int x;
void one();
void two();
main()
{
x=10;
printf("x in main is %d\n",x);
one();
two();
printf("x in main is %d\n",x);
}
void one()
{
int x=20;
printf("x in one is %d\n",x);
}
void two()
{
int x=30;
printf("x in two is %d\n",x);
}
OUTPUT:
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
x in main is 10
x in one is 20
x in two is 30
x in main is 10
When local variable and global variable are having the same name, then in the function in which
the local variable is declared, the global variable will not be effected that means local variable is
given highest priority than global variable.
Constant variable:- It is a variable whose value cannot be changed in the program. When a
variable is declared as a constant, we have to give initial value to that variable at the time of it’s
declaration.
ex:- main()
{
Const float pie=3.141592;
Printf(“pie=%f”,pie);
}
Static variable:- A static variable is variable which retains (or) gets it’s value between the
function calls. A Static variable initialized to zero when it is declared.
Syntax: Static datatype variable_name;
Ex:- static int x;
static float y;
static char c;
Void display();
main()
{
Int I;
for(i=1;i<=10;i++)
display();
}
void display()
{
static int count=1;
printf(“%d\t”,count);
count++;
}
OUTPUT:-
1 2 3 4 5 6 7 8 9 10
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
There are two ways in which we can pass arguments through a function
1) call by value mechanism
2) call by reference mechanism
call by value:- In call by value mechanism, when arguments are passing through called function,
then duplicate copies of actual arguments are created and those values are passed to called
function.
If any modification is done in the called function then those changes will effect only to
the variables which are declared in that function, those changes will not affect the actual
arguments because only values are passed to that function but not their addresses.
void exchange(int,int);
void main()
{
int a=10,b=20;
printf("before a=%d \t b=%d\n",a,b);
exchange(a,b);
printf("after a=%d \t b=%d\n",a,b);
}
void exchange(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
OUTPUT:
before a=10 b=20
after a=10 b=20
calling convention:- calling convention indicates the order in which the arguments are passed
to called function. Then the ‘c’ language follows is 2nd order
OUTPUT:
12 12 10
Call by reference:- In this mechanism, the values of actual arguments are not passed to the
called function but their addresses are passed through the called function. Then any
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
modification which is done in the actual function will affect the actual arguments that is present
in the calling function, why because the parameters in the called function are now pointing to
the arguments present in the called function.
Ex:-
OUTPUT:
before a=10 b=20
after a=20 b=10
Default arguments:-
#include<stdio.h>
void display( int =10,int =50,int =100);
int main()
{
display(10,20,30);
display(10,20);
display(10);
display();
}
void display(int a, int b,int c)
{
printf("%d %d %d\n",a,b,c);
}
OUTPUT:
10 20 30
10 20 100
10 50 100
10 50 100
note: -this program works in .cpp environment only.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
1) Actual parameters/arguments.
2) Formal parameters/arguments.
3) Dummy parameters/arguments.
Actual parameters:- Actual parameters are the parameters that are present in the calling
function, and these values are passed to called function when that function is called.
Formal parameters:- Formal parameters are present in the called function, and are used to
receive the values that are passed from calling function when that function is called.
Dummy parameters:- Dummy parameters are present in the function prototype, since they don’t
receive any values, the arguments in the function prototype are called dummy parameters.
Ex:- void display(int,float,char) // here int, float,char are dummy parameters.
main()
{
display(10,3.4,’+’); // here 10,3.4,+ are actual parameters.
}
void display(int a,float b,char c)
{
Printf(“%d %f %c”,a,b,c); //here int a,float f, char c are formal parameters.
}
Argument:- It is a value present in the calling function, which is passed to called function.
Parameter:- It is a variable present in called function to receive the value from calling function.
Void:-
1) The “void” keyword that is present before the function definition specifies that, that
function is not going to return any value.
2) The void keyword that is present in the parenthesis of a function indicates that the
function doesn’t take any arguments.
Ex:-
void hello(void); (or) void hello()
main() main()
{ {
hello(); hello(void);
} }
void hello() void hello(void)
{ {
printf(“hello”); printf(“hello”);
} }
Default return type:- the default return type of any function in c- language is “int”.
Local variables:- A variable which is declared in a function becomes local to that function. The
scope and lifetime of the local variable will be in existence only when the function is running in
which it is declared.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
{
Int x=10;
printf(“x in main=%d”,x);
hello();
}
void hello()
{
Int y=20;
printf(“ y in hello is %d”,y);
}
Here x & y are local variables. X belongs to only main function and y belongs to only hello
function.
When a program is done using recursion, then there must be any if statement written in that
function which is used to break the recursion process i.e. to exit from the function. Otherwise,
that the function is executed infinite times.
main()
{
int n,fact,m;
printf("enter a number\n");
scanf("%d",&n);
m=n;
for(fact=1;n>=1;n--)
fact=fact*n;
printf("factorial of %d is %d",m,fact);
}
OUTPUT:
enter a number
5
factorial of 5 is 120
recursion:
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
int factorial(int);
main()
{
int n,fact;
printf("enter a number\n");
scanf("%d",&n);
fact=factorial(n);
printf("factorial of %d is %d",n,fact);
}
int factorial(int n)
{
int f;
if(n==1)
return 1;
else
f=n*factorial(n-1);
return f;
}
OUTPUT:
enter a number
6
factorial of 6 is 720
Write a program to find sum of digits of a given number using recursion.
main()
{
int n,a,sum=0;
printf("enter a number\n");
scanf("%d",&n);
while(n>0)
{
a=n%10;
sum=sum+a;
n=n/10;
}
printf("%d",sum);
}
OUTPUT:
enter a number
113
5
Recursion:
int sumd(int);
main()
{
int n,sum=0;
printf("enter a number\n");
scanf("%d",&n);
sum=sumd(n);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
enter a number
123
the sum of digits 123 is 6
void fib(int,int,int);
main()
{
int n;
printf("enter a number\n");
scanf("%d",&n);
fib(0,1,n);
}
void fib(int a,int b,int n)
{
int c;
c=a+b;
if(c>n)
return;
else
{
printf("%d\t",c);
a=b;
b=c;
fib(a,b,n);
}
}
OUTPUT:
enter a number
8
1 2 3 5 8
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
main()
{
int m,n,res;
printf("enter the values for m and n\n");
scanf("%d %d",&m,&n);
res=gcd(m,n);
}
gcd(int m,int n)
{
if(m%n==0)
printf("the gcd is %d",n);
else
gcd(n,m%n);
}
OUTPUT:
enter the values for m and n
45
9
the gcd is 9
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
When a variable is declared under automatic storage class then that variable value is
stored in memory, the variable by default contains garbage value.
The scope of that variable is present only in that function or in that block, in which it is
declared.
The lifetime of that variable will remain in existence only when the block (or) the function
is running in which a variable is declared.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
OUTPUT:
2
1
error
1
Variables which are declared under this class are accessed faster than variables which
are declared using other storage classes.
Register storage class is used whether we require retrival of variables value faster.
In general, register storage class are used to develop loop counter variables.
Register storage class is not used for all the data types, it is used only for integers and
character values.
Because register has a capacity of max 16bits, registers cannot hold the values of float,
double, and long double.
Example:
#include<stdio.h>
main()
{
register int a=1;
{
register int a=2;
printf(“%d”,a);
}
printf(“%d”,a);
}
OUTPUT:
2 1
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Storage: memory
Default value: zero
Scope: local to block, function in which it is defined.
Lifetime: persists value between function calls.
Example:
#include<stdio.h>
main()
{
static int a=1;
{
static int a=2;
printf(“%d”,a);
}
printf(“%d”,a);
}
OUTPUT:
2 2
Storage: memory
Default value: zero
Scope: global (during entire program)
Lifetime: exists during the entire program.
Example:
#include<stdio.h>
extern int x;
void one();
main()
{
printf(“%d\n”,x);
x=100;
one();
}
void one()
{
printf(“%d”,x);
}
OUTPUT:
0
100
STRINGS
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
A string is a collection of characters/ group of characters that ends with a null character.
A string is an array of characters that ends with a null character.
Ex: India
The null character is present at the end of string/ character array.
The null character is represented by ‘\0’.
The ASCII value of null character is zero.
The purpose of null character is it indicates that, that is the end of string.
Char name[10]=”RVRJC”;
Char name[ ]=”RVRJC”;
Char name[10]={‘R’,’V’,’R’,’J’,’C’};
Char name[ ]={‘R’,’V’,’R’,’J’,’C’};
Write a program to read a string and print the string in different ways
#include<stdio.h>
main()
{
char name[]="India";
int i;
for(i=0;i<5;i++)
printf("%c",name[i]);
for(i=0;name[i]!='\0';i++)
printf("%c",name[i]);
printf("%s",name);
puts(name);
}
Output:
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
main()
{
char str[20];
for(i=0;i<10;i++)
scanf(“%c”,&str[i]);
puts(str);
scanf(“%s”,&str);
puts(str);
scanf(“%s”,str);
puts(str);
gets(str);
puts(str);
}
NOTE: If the no of characters entered in the string is lessthan the string size, then
compiler places a null character at the first empty location in the string.
Ex: char str[10]=”RVR”;
strlen(): This function is used to find the length of string.i.e no of characters present in it;
This function return no of characters in the string expect null character.
Syntax: strlen(string);
OUTPUT
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
2. Write a program to find length of string with out using library function
#include<stdio.h>
main()
{
char str[20];
int i,length=0;
printf("\nEnter a string");
gets(str);
for(i=0;str[i]!='\0';i++)
length++;
printf("Length of string=%d",length);
}
OUTPUT
Enter a string : krishna
Length of string=7
strcpy () :- This function is used to copy contents of one string into another string.
Syntax:- strcpy(string1,string2);
Destination source
3. Write a program to copy one string into another string using library function.
#include<stdio.h>
#include<string.h>
main()
{
char str[10],temp[10];
printf(“\nEnter a string:”);
gets(str);
strcpy(temp,str);
puts(str);
puts(temp);
}
OUTPUT
Enter a string: Anil kumar
Anil kumar
Anil kumar
4. Write a program to copy one string into another string without using library function.
#include<stdio.h>
main()
{
char str[10],temp[10];
int i;
printf(“\nEnter a string:”);
gets(str);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
for(i=0;str[i]!=’\0’;i++)
{
temp[i]=str[i];
}
temp[i]=’\0’;
puts(str);
puts(temp);
}
OUTPUT
Enter a string: Anil kumar
Anil kumar
Anil kumar
strcat():- This function is used to concatenate two string values i.e. contents of one string are
attached with the contents of another string.
Syntax:- strcat(string1,string2);
Here contents of string2 are append to contents of string1.
The string concatenation function replaces the null character in the first string and appends the
second string from that point onwards.
6. Write a program to concatenate two strings with out using library function.
#include<stdio.h>
main()
{
char s1[30]=”ANIL”,s2[30]=”KUMAR”,s3[30]=”ARUN”;
int i,j;
for(i=0;s1[i]!=’\0’;i++)
{}
for(j=0;s2[j]!=’\0’;j++)
{
s1[i]=s2[j];
i++;
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
}
for(j=0;s3[j]!=’\0’;j++)
{
s1[i]=s3[j];
i++;
}
s1[i]=’\0’;
puts(s1);
}
OUTPUT
ANILKUARARUN
OUTPUT
ANIL
LINA
8. Write a program to reverse the contents of a string without using library function
main()
{
char str[20],temp;
int i,j,length;
puts(“Enter a string :”);
scanf(“%s”,str);
length=strlen(str);
for(i=0,j=length-1;i<j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
puts(str);
}
OUTPUT
ANIL
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
LINA
strcmp():- This function is used to compare two string values whether they are equal, which one
is bigger or smaller string. This function returns zero value if both strings are equal, it returns
less than zero value or negative value, if the first string is less than second string. it returns
greater than zero value if the first string is greater than second string.
Syntax:- strcmp(string1,string2);
It performs comparison on the two strings based on the ASCII value of the characters
present in the string.
10. Write a program to compare two strings with out using string library functions
#include<stdio.h>
main()
{
char str1[20],str2[20];
int i,j;
printf(“Enter string1:”); gets(str1);
printf(“Enter string1:”); gets(str1);
i=j=0;
while(str[i]!=’\0’ || str2[j]!=’\0’)
{
if(str1[i]>str2[j])
{
printf(“%s > %s”,str1,str2);
exit(0);
}
else if(str1[i]<str2[j])
{
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
strlwr():- This function is used to convert uppercase letters in a string into lowercase.
Syntax:- strlwr(string);
11. Write a program to convert a string into lowercase using library function.
#include<string.h>
main()
{
char str[20];
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”);
puts(str);
strlwr(str);
printf(“After conversion:”);
puts(str);
}
OUTPUT:
Enter a string:ANIL
Before conversion: ANIL
After conversion: anil
12. Write a program to convert a string into lowercase using library function.
#include<string.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”); puts(str);
for(i=0;str[i]!=’\0’;i++)
if(isupper(str[i])
str[i]=tolower(str[i]);
printf(“After conversion:”); puts(str);
}
OUTPUT:
Enter a string:ANIL
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
13. Write a program to convert a string into lowercase without -using library function.
#include<stdio.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”); puts(str);
for(i=0;str[i]!=’\0’;i++)
if(str[i]>=’A’ && str[i]<=’Z’)
str[i]=str[i]+32;
printf(“After conversion:”); puts(str);
}
OUTPUT:
Enter a string:ANIL
Before conversion: ANIL
After conversion: anil
strupr():- This function is used to convert lowercase letters in a string into uppercase.
Syntax:- strupr(string);
14. Write a program to convert a string into uppercase using library function.
#include<stdio.h>
#include<string.h>
main()
{
char str[20];
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”);
puts(str);
strupr(str);
printf(“After conversion:”);
puts(str);
}
OUTPUT:
Enter a string:anil
Before conversion: anil
After conversion: ANIL
15. Write a program to convert a string into uppercase using library function.
#include<stdio.h>
#include<string.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
OUTPUT:
Enter a string:anil
Before conversion: anil
After conversion: ANIL
16. Write a program to convert a string into uppercase without -using library function.
#include<stdio.h>
main()
{
char str[20]; int i;
printf(“\nEnter a string:”);
scanf(“%s”,str);
printf(“ Before conversion:”); puts(str);
for(i=0;str[i]!=’\0’;i++)
if(str[i]>=’a’ && str[i]<=’z’)
str[i]=str[i]-32;
printf(“After conversion:”); puts(str);
}
OUTPUT:
Enter a string:anil
Before conversion: anil
After conversion: ANIL
}
here ‘size’ is optional.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
#include<stdio.h>
void read(char [20]);
void display(char []);
main()
{
char str[20];
read(str);
display(str);
}
output:
Enter a string: sai krishan
The string is: sai Krishna
#include<stdio.h>
void read(char [20]);
void display(char []);
void palindrome(char []);
main()
{
char str[20];
read(str);
display(str);
palindrome(str);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
puts(s);
}
output:
Enter a string: madam
The string is: madam
The string is palindrome
Here variable name indicates name of the double dimensional character array. Here row size
indicates no of strings it can store and column size indicates the size of each string.
Char names[10][20]={{‘I’,’N’,’D’,’I’,’A’,’\0’},
{‘A’,’S’,’I’,’A’,’\0’},
{‘E’,’U’,’R’,’O’,’P’,’E’,’\0’}};
char names[][20]={{‘I’,’N’,’D’,’I’,’A’,’\0’},
{‘A’,’S’,’I’,’A’,’\0’},
{‘E’,’U’,’R’,’O’,’P’,’E’,’\0’}};
char names[10][20]={“INDIA”,”ASIA”,”EUROPE”};
char names[][20]={“INDIA”,”ASIA”,”EUROPE”};
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Write a program to print the contents of double dimensional character array in different ways.
#include<stdio.h>
main()
{
char names[][20]={"ASIA","EUROPE","INDIA"};
int i,j;
/* first way*/
for(i=0;i<3;i++)
{
for(j=0;names[i][j]!='\0';j++)
printf("%c",names[i][j]);
printf("\n");
}
/* second way*/
for(i=0;i<3;i++)
{
for(j=0;j<strlen(names[i]);j++)
printf("%c",names[i][j]);
printf("\n");
}
/* third way*/
for(i=0;i<3;i++)
printf("%s\n",names[i]);
/* fourth way*/
for(i=0;i<3;i++)
puts(names[i]);
output:-
ASIA EUROPE INDIA
ASIA EUROPE INDIA
ASIA EUROPE INDIA
ASIA EUROPE INDIA
#include<stdio.h>
main()
{
char names[10][20];
int i,j;
/* first way*/
for(i=0;i<3;i++)
for(j=0;j<10;j++)
scanf("%c",&names[i][j]);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
for(i=0;i<3;i++)
puts(names[i]);
/* second way*/
for(i=0;i<3;i++)
scanf("%s",names[i]);
for(i=0;i<3;i++)
puts(names[i]);
/* third way*/
for(i=0;i<3;i++)
gets(names[i]);
for(i=0;i<3;i++)
puts(names[i]);
}
Write a program to print number of times the given name is present in a double dimensional
character array.
#include<stdio.h>
main()
{
char names[10][20],temp[20];
int i,n,c=0;
printf("\nEnter no of names");
scanf("%d",&n);
for(i=0;i<n;i++)
gets(names[i]);
for(i=0;i<n;i++)
if(strcmp(names[i],temp)==0)
c++;
if(c>0)
printf("No of times %s occured=%d",temp,c);
else
printf("%s is not found:",temp);
}
Output:-
Enter no of names:4
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Anil
Anil
Sunil
Anil
The names are:
Anil
Anil
Sunil
Anil
Enter the searching string: Anil
No of times Anil occurred=3.
Enter no of names:4
Anil
Anil
Sunil
Anil
The names are:
Anil
Anil
Sunil
Anil
Enter the searching string: Kumar
Kumar is not found.
Write a program to read and print the students names using functions.
#include<stdio.h>
void readnames(char [][20],int);
void displaynames(char [][20],int);
main()
{
char names[30][20];
int n;
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
readnames(names,n);
displaynames(names,n);
}
#include<stdio.h>
void read(char [][20],int);
void display(char [][20],int);
void sort(char [][20],int);
main()
{
char names[30][20];
int n;
read(names,n);
printf("Before sorting names are:");
display(names,n);
sort(names,n);
printf("After sorting names are;");
display(names,n);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
int i;
for(i=0;i<n;i++)
{
printf("Enter %d names",i+1);
gets(names[i]);
}
}
void display(char names[][20],int n)
{
int i;
printf("\nThe names are:\n");
for(i=0;i<n;i++)
puts(names[i]);
}
void sort(char names[][20],int n)
{
char temp[20];
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(strcmp(names[j],names[j+1])>0)
{
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}
}
Write a program to sort the given names alphabetically in ascending order according to their
length..
if(strlen(names[j],names[j+1])==0)
{ (same as above)
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}
POINTERS
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
A pointer is a variable, which holds the address of another variable of the same type.
Advantages of pointers
Pointer initialization: The general syntax for pointer initialization is ptr variable name = &variable
name;
Ex: int a=10; Float pi=3.14; char *x;
Int *p; float *q; char r;
P=&a; q=π x=&r;
Declaration and initialization of pointer variable: ex: int a=10; int *p=&a;
#include<stdio.h>
main()
{
int a=10;
int *p=&a;
printf(“address of a=%u\n”,&a);
printf(“address of a=%u\n”,p);
printf(“address of a=%u\n”,&p);
printf(“address of a=%u\n”,a);
printf(“address of a=%u\n”,*(&a));
printf(“address of a=%u\n”,&p);
}
o/p: Address of a =1000
Address of a =1000
Address of a =2000
Value of a =10
Value of a =10
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Value of a =10
#include<stdio.h>
main()
{
int a=10;
int *p=&a;
int *q=p;
printf(“ a=%d”,a);
printf(“ a=%d”,*(&a));
printf(“ a=%d”,*p);
printf(“ a=%d”,*q);
*q=200;
printf(“ a=%d”,a);
}
#include<stdio.h>
main()
{
int a=10;
int *p=&a;
int **q=&p;
int ***q=&q;
printf(“ Address of a=%u\n”,&a);
printf(“ Address of a=%u\n”,p);
printf(“ Address of a=%u\n”,*q);
printf(“ Address of a=%u\n”,**r);
printf(“ Address of p=%u\n”,&p);
printf(“ Address of p=%u\n”,q);
printf(“ Address of p=%u\n”,*r);
printf(“ Address of q=%u\n”,&q);
printf(“ Address of q=%u\n”,r);
printf(“ Address of r=%u\n”,&r);
}
o/p: Address of a=1000
Address of a=1000
Address of a=1000
Address of a=1000
Address of p=2000
Address of p=2000
Address of p=3000
Address of q=3000
Address of q=3000
Address of r=4000
#include<stdio.h>
main()
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
{
int a=10;
int *p=&a;
int **q=&p;
int ***r=&q;
printf(“ a=%d”,a);
printf(“ a=%d”,*(&a));
printf(“ a=%d”,*p);
printf(“ a=%d”,**q);
printf(“ a=%d”,***r);
}
o/p:
a=10
a=10 a=10 a=10 a=10
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
int *fun();
main()
{
int *p
p=fun();
printf(“a=%d”,*p);
}
int *fun()
{
int a=10;
return &a;
}
o/p:a=10
int **fun();
main()
{
int **p
p=fun();
printf(“a=%d”,**p);
}
int *fun()
{
int a=10;*p;
return &p;
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
o/p:a=1264036
char ***fun();
main()
{
char ***r
r=fun();
printf(“%c”,***r);
}
char ***fun()
{
char s=’+’;
char *p=&s;
char **q=&p;
return &q;
}
o/p:+
main()
{
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<5;i++)
printf(“%u %d %u %d”,&a[i],a[i],(a+i),*(a+i));
}
a[i]=*a(p+i)
a[0]=*(p)
a[0]=*(1000)
a[0]=10
a[i]=*(a+i)
a[i]=*(1000+2)
a[i]=20
main()
{
int a[5]={10,20,30,40,50};
int i,*p;
p=&a[0];
for(i=0;i<5;i++)
printf(“%d\n”,p[i]);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
o/p:10 20 30 40 50
main()
{
int a[]={10,20,30,40,50};
int i,*p;
p=&a[0]; (or) p=a;
for(i=0;i<5;i++)
{
printf(“%d\n”,p[i]);
p++;
}
}
o/p:10 20 30 40 50
main()
{
char s[10];
char *p;
s=”hello”; * incompatible type argument
p=”hello”
puts(p);
o/p:hello
main()
{
char s[10]=”hello”,str2[10];
char *s1=”hello”,*s2;
str2=str1; * incompatible type argument
s2=s1;
puts(s1);
puts(s2);
o/p:hello
o/p:hello
It returns the address of the variable. The operand may be variable, a constant.
Ex: int n,*m;M=&n;
Hence address of n is assigned to m; This ‘m’ is not a ordinary variable, it is a variable which
holds the address of other variable.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Static memory allocation (SMA) :- The process of allocating memory to variables at compile
time is called SMA (or) compile time allocation.
0 1 2 3 4
10 20 30 40 50
1000 1002 1004
0 1 2 3 4 5 6 7 8 9
10 20
1000 1002
nd th
in the above figure from 2 cell to 9 cell wastage of memory is arising.
Dynamic memory allocation (DMA) :- the process of allocating memory to variables at the
runtime is called DMA (or) runtime allocation.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Code space
Stack space
Separate storage
Malloc():- this function is used to allocate required no.of bytes to the variable at run time.
int *a;
a=(int *) malloc(5*sizeof(int));
a 0 1 2 3 4
10
5 * 2 = 10 bytes of memory is created and starting address of that is created memory it passed to a.
float *b;
b=(flaot *) malloc(10* sizeof(flaot));
b 0 1 2 3 4 5 6 7 8 9
10
100 104 108 ……………………………………….
100 10*4= 40 bytes.
char *c;
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
10
2000
0 1 2 3 ………………………………………………..
main()
{
int *a,I,n;
printf(“enter the no.of elements\n”);
scanf(“%d”,&n);
a=(int *) malloc(n * sizeof(int));
printf(“enter the array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i); // &a[i]
printf(“the array elements are\n”);
for(i=0;i<n;i++)
printf(“%d”,*(a+i)); // a[i]
}
Calloc() :- This function is used to allocate required amount of memory to the variable at runtime.
This function allocates a no. of individual continues memory allocations to the variables.
Syntax: pointer_variable = (datatype *) calloc((no.of elements * sizeof(datatype));
A 0 1 2 3 4
10
100
100 102 104 106 108
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
realloc(): This function is used to allocate memory to the variables again at runtime.
Ex: #include<stdio.h>
#include<stdlib.h>
main()
{
char *s;
s=(char*)calloc(5,sizeof(char));
strcpy(s,”HELLO”);
puts(s);
s=(char *)realloc(s,9);
strcpy(s,”HELLO HAI”);
puts(s);
}
output:
HELLO
HELLO HAI
free(): This function is used to delete or to deallocate the allocated memory for the pointer
variable.
Syntax: free(pointervariable);
Ex: #include<stdio.h>
main()
{
float *a;
a=(float*)malloc(5*sizeof(float));
if(a==NULL)
{
printf(“Memory is not allocated”);
}
else
{
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
printf(“Memory is allocated”);
}
free(a);
}
output:
Memory is allocated.
Int a[2][2]={{10,20},30,40}};
0 1
A[0] 10 20
A[1] 30 40
10 th address = &a[0][0]=a[0]+1=1000+0*2=1000
20 th address = &a[0][1]=a[0]+1=1000+1*2=1002
30 th address = &a[1][0]=a[1]+1=1004+0*2=1004
40 th address = &a[1][1]=a[1]+1=1004+1*2=1006
Address Values
&a[i][j] =a[i]+j a[i][j]=*(a[i]+j)
=*(a+i)+j =*(j+a[i])
=j+*(a+i) =*(j+*(a+i))
=*(*(a+i)+j)
Ex: #include<stdio.h>
main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i;
for(i=0;i<3;i++)
printf(“a[%d] array address=%u”,i,a[i]);
}
output:
a[0] array address=1000
a[1] array address=1004
a[2] array address=1008
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
main()
{
int a[5][5],m,n,i,j;
printf("Enter no of rows and columns:\n");
scanf("%d%d",&m,&n);
printf("Enter matrix elements are:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nThe matrix elements are:");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d",a[i][j]);
}
}
output:
Enter no of rows and columns: 2 2
Enter matrix elements are: 10 20 30 40
The matrix elements are:
10 20
30 40
Write a program to read and print matrix elements using array of pointers and dynamic
memory allocation.
main()
{
int *a[10];
int i,j,m,n;
printf("Enter the size of the matrix:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
a[i]=(int *)malloc(n*sizeof(int));
printf("Enter matrix elemnts are:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",*(a+i)+j);
printf("\n");
printf("\nthe matrix elements are:");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d",*(*(a+i)+j));
}
}
output:
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
#include<stdio.h>
main()
{
int a[4][2]={{10,20},{30,40}};
int *p,i,j;
//p=a;
p=&a[0][0];
p=a[0];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%d",*(p+i*2+j));
printf("\n");
}
}
output:
10 20
30 40
Write a program to read and print different strings using pointers and dynamic memory
allocation:
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
for(i=0;i<n;i++)
puts(names[i]);
}
output:
Enter no of names:
5
Enter names:
Enter 0 name:ANIL
Enter 1 name:Kumar
Enter 2 name:Kiran
Enter 3 name:Dileep
Enter 4 name:Vasu
The names are:
ANIL
Kumar
Kiran
Dileep
Vasu
Ragged array: Arrays having varying length in columns are called as ragged arrays.
Write a student data file(rollno, name, rank, date of birth) and code a program
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
#include<stdio.h>
#include<string.h>
struct student
{
char name[10];
int rno;
int rank;
struct dateofbirth
{
int day;
int month;
int year;
}dob;
};
void read(struct student *s[],int);
void display(struct student *s[],int);
void sortnames(struct student *s[],int);
void sortdob(struct student *s[],int);
void sortnamesdob(struct student *s[],int);
void swap(struct student *,struct student *);
main()
{
struct student *s[10];
int i,n,ch;
printf("Enter no of students:\n");
scanf("%d",&n);
while(1)
{
printf("1.Read\n2.Display\n3.Sort by names\n4.Sort by dob\n");
printf("\n5.Sort by names dob\n6.Exit\n");
printf("Enter your choice::\n");
scanf("%d",&ch);
switch(ch)
{
case 1:read(s,n);break; case 2:display(s,n);break;
case 3:sortnames(s,n);break; case 4:sortdob(s,n);break;
case 5:sortnamesdob(s,n);break; case 6:exit();break;
}
}
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
{
int i;
for(i=0;i<n;i++)
{
s[i]=(struct student*)malloc(sizeof(struct student));
printf("Enter %d student details:\n",i+1);
printf("Enter name:\n");
scanf("%s",s[i]->name);
printf("Enter Rollno\t Rank\t");
scanf("%d%d",&s[i]->rno,&s[i]->rank);
printf("Enter dob(dd-mm-yyyy)\n");
scanf("%d%d%d",&s[i]->dob.day,&s[i]->dob.month,&s[i]->dob.year);
}
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
else if(s[j]->dob.year==s[j+1]->dob.year)
{
if(s[j]->dob.month>s[j+1]->dob.month)
swap(s[j],s[j+1]);
else if(s[j]->dob.month==s[j+1]->dob.month)
{
if(s[j]->dob.day>s[j+1]->dob.day)
swap(s[j],s[j+1]);
}
}
display(s,n);
}
if(s[j]->dob.year>s[j+1]->dob.year)
swap(s[j],s[j+1]);
else if(s[j]->dob.year==s[j+1]->dob.year)
{
if(s[j]->dob.month>s[j+1]->dob.month)
swap(s[j],s[j+1]);
else if(s[j]->dob.month==s[j+1]->dob.month)
{
if(s[j]->dob.day>s[j+1]->dob.day)
swap(s[j],s[j+1]);
}
}
}
display(s,n);
}
STRUCTURES
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
A structure is a user defined data type which can store elements of different data types
(or) same data types.
struct structurename
{
datatype var1;
…..
….
Datatype var2;
}
Eg:- struct student struct employee
{ {
char name[20]; char name[20];
int rno; int id;
}; float salary;
};
Syntax for creating structure variables:-
S1 S2
name[20] name[20]
rno rno
22 bytes 22 bytes
Accessing structure members:-
struct student
{
char name[20]; members of structures
int rno;
};
struct student s;
(.) dot operator
s.rno;
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
1) #include<stdio.h>
main()
{
struct student
{
char name[20];
int rno;
};
struct student s1={“aa”,825};
struct student s2={“bb”,826};
printf(“s1 derails \n”);
printf(:%s %d”, s1.name, s1.rno);
printf(“s2 derails \n”);
printf(“%s %d”, s2.name, s2.rno);
}
O/P:-
s1 details S1 S2
aa 825
s2 details Name: aa Name: bb
bb 826 Rno: 825 Rno: 826
2) #include<stdio.h>
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
main()
{
struct student
{
char name{20];
int rno;
}s1={“aa”, 825}, s2={“bb”, 826};
printf(“s1 details \n”);
printf(“ %s %d”,s1.name, s2.name);
printf(“s2 detials \n”);
printf(“ %s %d”, s2.name, s2.name);
}
3) #include<stdio.h>
main()
{
struct
{
char name[20];
int rno;
}s1={“aa”, 825}, s2={“bb”, 826};
printf(“s1 detials \n”);
printf(“%s %d”, s1.name, s1.rno);
printf(“s2 details \n”);
printf(“%s %d”, s2.name, s2.rno);
}
4) #include<stdio.h>
main()
{
struct
{
char name{20];
int rno;
}s1,s2;
strcpy(s1.name, “aa”);
s1.rno=825;
strcpy(s2.name, “bb”);
s2.rno=826;
}
Array of structures:-
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
0 1 2 3 9
s
name name
rno rno
struct student
{
char name[20];
int rno;
};
main()
{
struct student s[20];
int i, n;
printf(“Enter no. of students “);
scanf(“ %d ”, &n);
for (i=0;i<n;i++)
{
printf(“Enter %d student details”, i+1);
printf(“Enter name:”);
gets(s[i].name); (or) scanf(“%s”, s[i].name);
printf(“Enter number:”);
printf(“%d”, &s[i].rno);
printf(“\n The student details are \n”);
for(i=0;i<n;i++)
printf(“%s %d\n”, s[i].name, s[i].rno);
}
}
O/P:-
Enter no. of students: 2
Enter 1 student details:
Enter name aa
Enter rno 825
Enter 2 student details:
Enter name bb
Enter rno 826
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
struct student
{
char name[20];
int rno;
}
void change (struct student);
main()
{
struct student s = {“aa”, 825};
printf(“ Before change”);
printf(“%s %d”, s.name, s.rno);
change(s);
printf(“After change”);
printf(“%s %d”, s.name, s.rno);
}
void change (struct student p)
{
strcpy (p.name, “bb”);
p.rno = 826;
}
O/P:-
Before change
aa 825
After change
bb 826
modifications
change (s);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
int n;
printf(“Enter no. of students”);
scanf(“%d”, &n);
read(s,n);
display(s,n);
}
Ex:-
struct student
{
char name[20];
int rno;
};
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
main()
{
struct student s={“aa”, 100}, t;
strcpy(t.name, s.name);
t.rno=s.rno;
puts(t.name);
printf(“%d”,t.rno);
}
O/P:-
aa
100
Ex:-
struct student
{
char name[20];
int rno;
};
main()
{
struct student s = {“aa”, 100},t;
t = s;
puts(t.name);
printf(“%d”, t.rno);
}
Write a program to read student marks and find his average and print the details in the
descending order according to the average.
Struct student
{
char name[20];
int rno;
int m,p,c;
float avg;
};
main()
{
struct student s[50];
int n;
printf(“Enter number of students\n”);
scanf(“%d”,&n);
read(s,n);
printf(“ Before finding average”);
display(s,n);
avge(s,n);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
write a program to find net salary for the number of employees and print them using
functions.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
struct student
{
char name[20];
Sint rno;
}
main( )
{t
struct student p;
p=fun( );
printf(“ %s %d”,p.name,p.rno);
}
struct student
{
char name[20];
int rno;
};
main( )
{
struct student **q;
q=fun( );
printf(“%s%d”,(*q)->name,(*q)->rno);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
write a program to add, sub, mul and div of two complex numbers.
struct complex
{
int real;
int img;
}
main()
{
struct complex c1,c2,c3,c4,c5,c6,c7;
printf(“ Enter first complex number\n”);
scanf(“%d%d’,&c1.read, &c1.img);
printf(“ Enter the second complex number”);
scanf(“%d%d’,&c2.read, &c.img);
printf(“ c1=”);
display(c1);
printf(“ c2=”);
display(c2);
c3=add(c1,c2);
printf(“c1+c2=”);
display(c3);
c4=sub(c1,c2);
printf(“c1-c2”);
display(c4);
c5=mul(c1,c2);
printf(“c1*c2=”);
display(c5);
c6=div(c1,c2);
printf(“c1/c2”);
display(c6);
}
void display( struct complex c)
{
printf(“%d+i%d”,c1.real,c1.img);
}
struct complexadd(struct complex x, struct complex y)
{
struct complex temp;
temp.real=x.real+y.real;
temp.img=x.img+y.img
return temp;
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
syntax:
struct structurename1
{
datatype var1;
.
.
.
.
datatype varn;
struct structurename2
{
datatype var1;
.
.
.
.
datatype varn;
};
.
.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
.
.
struct structurename n
{
datatype var1;
.
.
.
.
datatype varn;
};
};
example:
struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
};
};
struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
};
};
main( )
{
struct student s={“aa”,825,28,3,2008};
printf(“%s %d %d %d %d”,s.name, s.rno, s.day, s.month, s.year);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
};
};
main( )
{
printf(“%s%d-%d-%d”, s.name, s.rno, s.day, s.month, s.year);
}
runtime initialization:
struct student
{
char name[20];
int rno;
struct date
{
int day;
int month;
int year;
}d;
};
main()
{
struct student s;
printf(“ Enter student name”);
gets(s.name);
printf(“Enter roll number”);
scanf(“%d”,&s.rno);
printf(“Enter details:”);
scanf(“%d%d%d”,&s.d.day,&s.d.month,&s.d.year);
printf(“%s%d%d-%d%d”,s.name,s.rno,s.d.day,s.d.month,s.d.year);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
struct student
{
char name[20];
int rno;
struct student *next;
};
A self-referential structure is one which contains a pointer to its own type.
Pointer structure:
Example1:
Struct student
{
char name[20];
int rno;
};
main()
{
struct student s,*p;
printf(“enter student details\n”);
gets(s.name);/* or gets(p->name); or gets((*p).name);*/
printf(“enter roll number”);
scanf(“%d”,&s.rno);/* &p->rno*/
printf(“\n student details are:\n”);
printf(“%s%d\n”,s.name,s.rno);
printf(“%s%d\n”,(*p).name,(*p).rno);
}
Example2:
Struct book
{
char title[20];
int pages;
float price;
};
main(0
{
struct book B,*p;
p=&B;
strcpy(B.title,” C made easy”);
strcpy(B.author,”Herbert skhildt”);
B.pages=250;
B.price=230.50;
record(p);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Struct p,*p1;
P1=&p;
Here p1 which is a pointer to a structure is assigned the address of the structure variable
person p.
Structure members may be accessed using pointers to structures by the use of special
operators ->(arrow operator).
Struct student
{
char name[20];
int rno;
}
UNIONS:
A union is a user defined data type. Which is used to store elements of different data types.
Syntax:
union name
{
datatype var1;
.
.
datatype varn;
};
union follows the same syntax as structures, and are declared the keyword union.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Example:
union mem
{
int a;
float b;
char c;
};
in this declaration ‘b’ requires 4 bytes,because it is of float type.This is largest storage for
union.the compiler allocates a storage place to hold enough the largest number.
Struct student
{
char name[20];
int rno;
float marks;
};
main()
{
struct student s;
printf(“size of s=%d”,sizeof(s));
}
union student
{
char name[20];
int rno;
float marks;
};
main()
{
union student s;
printf(“size of s=%d”,sizeof(s));
};
struct student
{
char name[20];
int rno;
struct student *next;
};
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
main()
{
struct student *s;
s=(struct student *) malloc(sizeof((struct student));
strcpy(s->name,”hello”);
s->rno=825;
s->next=(struct student *)malloc(sizeof(struct student));
}
Enum dept
{
Physics, chemistry, zoology;
}
Program:
#include<stdio.h>
main ()
{
enum day
{
sun,mon,tue,wed,thu,fri,sat;
};
enum day day1;
day1=sat;
If (day1==sat!! day1==sun)
Print (“holyday”);
Else
Printf (“working day”);
day1=3; /* Wednesday */
If (day==0!! day1==6)
Printf (“holiday”);
Else
Printf (“\n working day”);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
3. main ()
{
int I, count=0;
For (i=0;i<10;i++)
{
Count=count+5;
}
Printf (“%d%d”, I, count);
}
Null pointer: - it is a pointer whose value is initialization to zero is called null pointer.
Ex;-main ()
{
Int *p=0;
}
Dazzling pointer:- A pointer whose value is not initialized is know as dazzling pointer.
Enumerated data types: it is used to assign name to constants or giving values to names.
It is represented by keyword –enum;
Eg:- 1.enum{
Off 0;
On 1;
};
2. Enum shap
{
Circle 0
Line 1;
Double line 2
Triangle 3;
Square 4;
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
3. Enum
{
White, 0;
Black=100;
Blue;
Green=200;
Red;
Violet;
}
Structures union
1. Each member occupies its own memory All the memory use the same memory space
Space.
2. Struct keyword in used to define a structure. Union keyword id used to define a
union.
3. All the members can be initialized. Only the first member can be
initialized.
4. The members are stored in continuous the members are stored in continuous
memory locations. locations
Arrays Structures
Individual members must be linked to the structure variables in order to make then more
meaningful.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Files
A file is a defined data type used as data structure.
A file is also known as a string.
Files are used to stored data permanently to the external stores devices such as
floppy disc and
Also to read data from external storage devices.
Operations on files:-
File Pointers:
File pointer in the internal name or logical name given to the file which is opened
for specific purpose.
File *filepointername;
Fopen ();- This function is used to open a file in the specified mode.
Syntax:-
File pointer=fopen (“filename”,” opening mode”);
Mode Symbol
Read “r”
Write “w”
Append “a”
Read write “r*”
Write read “w+”
This function returns file descriptor to the file pointer if the file in opened
successfully, otherwise it returns null pointer.
Fclose ():
FILE ACCESSING:
1. Sequential accessing.
2. Random Accessing.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
1. putc()
2. fputc()
3. getc()
4. fgetc()
5. fputs(0
6. fgets()
7. fprintf()
8. fscanf()
9. fwrite()
10. fread()
11. feof()
1. fseek()
2. ftell()
3. rewind()
Putc ():-- This function is used to write character by character into the file.
Write a program to write and read some text into file character by character.
#include<studio.h>
main ()
{
File *fp;
Char ch;
Fp=fopen (“fruits.c”,”w”);
Ch=getchar ();
While (ch! =EOF)
{
Putc (ch, fp);
Ch=getchar ();
}
Fclose (fp);
Fp=open (“fruits.c”,”r”);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Ch=getc (fp);
While (ch! =EOF)
{
Printf (“%c”, ch);
Ch=getc (fp);
}
Fclose (fp);
}
Feof ():--This function is used to indicate end of file. This function returns zero, if the end office
is not reached. This function returns non-zero, if the end of file is reached.
Syntax:-feof (fp);
Fputs ():--This function is used to write a string into the file.
Syntax:- fgets(string,no.characters,fp);
Write a program to write and read contents into the file or to demonstrates fputs () and fgets ().
main ()
{
File **P;
Char str [20];
Int i, n;
Printf (“enter the no of strings :”);
Scanf (“%d:, &n);
Fp=fopen (“fruits.c:,”w”);
` for (i=1;i<=n;i++)
{
Printf (“enter the string”);
gets (str);
fputs (str, fp);
}
fclose (fp);
fp=fopen (“fruite.c”,”r”);
Printf (“The file contents “);
While (! feof (fp))
{
fgets (str, 5, fp);
Printf (“%s”, str);
}
fclose (fp);
}
fprintf ():--This function is used to write formatted input into the file.
Syntax:-fprintf (fp,”format specifiers”, arg1, arg2……argn);
Fscan ():--This function is used to read formatted out put from the file.
Syntax:--fscanf (fp,”formatspecifier”, &arg1, &arg2…&argn);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
#include<stdio.h>
main ()
{
File **p;
Char name [20];
Int rno, rank;
Int I, n;
Printf (“Enter the no. of students”);
Scanf (“%d”, &n);
Fp=fopen (“student.c”,”w”);
For (i=1; i<=n;i++)
{
printf (“Enter the name”);
gets (name);
Printf (“enter the rno, rank”);
Scanf (“%d%d”, &rno, &rank);
fprintf (fp,”%s\t%d\t%d\n”, name, rno, rank);
}
fclose (fp);
fp=fopen (“student.c”,”r”);
fscanf (fp,”%s\t%d\t%d\t”, &name, &rno, &rank);
While (! feof(fp))
Printf (“%s%d%d\n”, name, rno, rank);
fscanf (fp,”%s\t%d\t%d\t”, name, &rno, &rank):
}
}
fwrite ():--This is used to write an entire structure into file.
Struct student
{
Char name [10];
int rno, rank;
}
main ()
{
Struct student s;
Int i, n, temp;
File *fp;
Fp=fopen (“student.c”,”w”);
Printf (“enter no. of student details”, i+1);
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
rewind ():-This function is used to remove the file pointer to the starting position of the file.
Syntax:-rewind (fp);
#include<stdio.h>
main ()
{
File *fp;
Char ch;
Fp=fopen (“country.c”,”r”);
Printf (“file contents are”);
Ch=getc (fp);
While (! feof (fp))
{
putchr (ch);
Ch=gets (fp);
}
rewind (fp);
printf (“Again file contents are”);
ch=getc (fp);
While (! feof (fp))
{
Put char (ch);
ch=getc (ch);
}
fclose (fp);
}
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
ftell ():-this function is used to indicate the position of the file pointer. This function returns
the long integer value.
Syntax:-ftell (fp);
fseek ():-This function is used to move the file pointer either forwards or backwards to the
specified no. of byte the given position.
Here offset indicates no. of bytes to move from the given position.
Here position can take three values.
Ex:- #include<stdio.h>
main()
{
File *fp;
Char ch;
Fp=fopen (“alphabet.c”.”r”);
If (fp==null)
{
Printf (“file is not opened for reading”);
}
n=ftell (fp);
rintf (“fp ps=%d”, n);
fseek (fp, 5, 0);
rintf (“fp pos=%d”, ftell (fp));
fseek (fp, 2, 1);
rintf (“fp pos=%d”, ftellp));
fseek (fp, -7, 2);
rintf (“fp, ol, 0);
printf (“fp pos=%d”, ftell (fp));
}
fclose (fp);
}
Output:
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Fp pos=0;
Fp pos=5;
Fp pos=7;
Fp pos=19;
Fp pos=0;
The arguments which are given at the command prompt and are passed to the main function.
Here argc contain no. of arguments given at the command prompt. Argc is called
count. Argv is known as argument vector, which contains the arguments given at
the command prompt starting from zero.
11
‘c’ programming . R.V.R & J.C COLLEGE OF ENGINEERING.
Write a program to copy contents of one file into another file using command line arguments.
#include<stdio.h>
main (int argc, char *argv[])
{
File *fp1,*fp2;
Char ch;
If (argc!=3)
{
printf (“In sufficient no. of arguments”);
exit (0);
}
fp1=fopen (argv[1],”r”);
if (fp1==NULL)
{
Printf (“source file not opened”);
exit (0);
}
fp2=fopen (arg [2],”w”);
If (fp2==null)
{
Printf (“destination file is not appended”);
Exit (0);
}
ch=getc (fp1);
While (! feof (fp1))
{
Putc (ch, fp2);
ch=getc (fp1);
}
fclose(fp1);
fclose(fp2);
11