Académique Documents
Professionnel Documents
Culture Documents
COMPUTER: Computer is an electronic device, which has memory and performs arithmetic and logical
operations.
Input: The data entered in the computer is called input. Ex:- Keyboard, mouse, joy stick etc.,
Output: The resultant information obtained by the computer is called output. Ex:- Through Screen, Printer etc.,
Program: A sequence of instructions that can be executed by the computer is called program.
Software: A group of program to operate and control the computer is called software
Hardware: All the physical components or units of computer system connected to the computer circuit is called
hardware.
Operating System: It is an interface between user and the computer. In other words, operating system is a
complex set of programs, that manage the resources of a computer. Resource include input, output, processor
etc., So operating system is a Resource manager.
Language: It consists of a set of executable instructions.
Package: It is designed by any other language with limited resources.
26 ( A to Z)
26 (a to z)
10 ( 0 to 9)
32
34
128
Out of the 256 character set. First 128 are called ASCII Characters and the next 128 as extended
ASCII Characters each ASCII character has a unique appearance.
A to Z
65 to 90
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
a to z
0 to 9
Enter
Space
Tab
Back Space
97 to 122
48 to 57
13
32
9
8
Algorithm:-A step by step procedure to solve the given problem is known as algorithm.
1. To find the sum, product, and division of given two numbers.
Steps:-1. Read any two numbers a,b
2. sum=a+b
3. product=a*b
4. division=a/b
5. print sum, product, division
6. end
2. To find the maximum value of given two numbers:
Steps:1. Read any two values a,b
2. max=a
3. if max<b then max=b
4. print max
5. end
3. To find the maximum value of three numbers
Steps:1. Read any three values a,b,c
2. max=a
3. if max<b then max=b
a=10 b=20 c=5
4. if max<c then max=c
5. print max
6. end
4. To check whether the given number is even or odd
Steps:1. Read n
2. if n%2= = 0,
print n is even
else
print n is odd
3. end
5. To display natural numbers from 1 to given number
Steps:1. Read n
2.
3.
4.
5.
6.
i=1
print i
i=i+1
if i<=n then to to step3
end
Steps:1. Read n
22
2. rev=0,m=n
m=22
3. rev=rev*10+(m%10)
2*10+(2%10)=22
4. m=m/10
22/10 =2
5. if n>0 then go to step3
6. if n= = rev then print n is palindrome
else
n is not palindrome
7. end
FLOW CHART
Definition: Graphical or Symbolic representation of given algorithm or problem
known as Flow Chart.
3. Rectangles are used to represent a data transfer operations and arithmetic operations (Processing)
6. Arrows indicator the directions to be followed in a flow chart. Every line in a flow chart must be an
arrow on it
3C LANGUAGE
C is a programming language it is designed by DENNIS RITCHIE in 1972 at AT & T [American
Telephone and telegraphs] Bell labs in USA. C is most popular general purpose language.
BRIEF HISTORY OF C LANGUAGE:
In 1960s COBOL was being used for commercial applications and FORTRAN for scientific and
engineering applications. At this stage people started to develop a language which is suitable for all possible
applications. Therefore an international committee was setup to develop such a language ALGOL 60 was
released. It was not the generality a new language called CPL [Combine Programming Language] was
developed at Cambridge University then some other features were added to this language a new language called
BCPL [Basic combine programming language] developed by MARTIN RICHARDS at Cambridge University.
Then B language was developed by KENTHOMSON at AT &T Bell labs.
DENNIS RITCHIED inherited the features of B and BCPL, added some of its own feature and
developed C language in 1972.
Features of C Language:
1.
C is structured programming language with fundamental flow chart constructions.
2.
C is highly portable programming language. The programs return for one computers can be run on
another with or without any modifications.
3.
The programs return in C are efficient and fast.
4.
C improves by itself it has several predefined functions.
5.
C has only 32 keywords.
6.
C supports all data conversions and mixed mode operators.
7.
Dynamic memory storage allocation is possible with C.
8.
C is simple and versatile programming language.
9.
C easily manipulate with bytes, bits and address.
10.
11.
12.
13.
14.
Important Points
C is a case sensitive programming language. C statements are entered in lower case letters only.
Every C statement must be terminated by a semicolon ( ; ) except preprocessor statements and
function definition.
3.
C is a function oriented language. Any C program contains one or more functions. Mainly one
function is necessary by the name called main. Without main we cannot execute C Programs.
4.
A function is represented by a function name with a pair of parenthesis.
1.
2.
C source
program(.c)
Compiler
Output
Object file
(.obj)
Primary
memory
(Ram)
LINKER
Executable
File(.exe)
LOADING
Start Program
Execution
Processor
Once the coding is completed, the program is feed into the computer using a compiler to produce
equivalent machine language code.
In C compilation two parts are there namely 1) Compiler and 2) Linker.
Compiler receives C source file as input and converts the file into object file. Then the linker receives
that object file as input and linking with C libraries after linking it produces executable file. After creation of
executable file then start the program execution and loads the information of the program in the primary
memory through loading process after loading the information the processor processing the information and
gives the output.
BASIC STRUCTURE OF C PROGRAM
[Document Section]
Pre-Processor section
Or
Link Section.
[Global declaration section]
Main()
{
[Local declaration section]
Statements
}
[Sub programming section]
[User Defined function]
Document Section: It consist the set of comment lines. The document section consists the set of comment lines
giving the name of the program, author name and other details.
Link Section: It provides instructions to the compiler to link the functions from the system library.
Global Declaration Section: The variables that are used in more than one function are known as global
variables and these variables are declared in the global declaration section.
Main( ) Section: Every C program must have one main function this section consists two parts namely local
declaration section and statement parts. The local declaration section declares all the variables used in
statements. The statement part consist a sequence of executable instructions. These two parts must appear
between the opening and closing curly braces. The program execution begins at the opening brace and end at
the closing brace.
Sub-Programming Section: This section consists all the user defined function.
Comments: Un executable lines in a program are called comments. These lines are skipped by the compiler.
//-------------------------------Single line comment
/*------------------------------*/
Group of lines comment
Pre-Processor statements:- The pre processor is a program that process the source code before it passes
through the compiler.
#include: It is a pre processor file inclusion directive and is used to include header files it provides instructions
to the compiler to link the functions from the system library.
Syntax: # include file name
Or
#include<file name>
When the file name is included with in double quotation, the search for the file is made first the current
directory and then the standard directories or the file name is included within angular bases then the file is
searched only in the standard directories.
Printf( ): It is a function and is used to print data on the screen.
Syntax: int printf(control sting,[arg-1,arg-2,..arg-n]);
Or
(format string)
The printf statement is used to print messages, the values contain in the variable on the screen.
stdio.h:- Standard input and output header file.
conio.h:-Consol input and output header file.
Example: printf(Welcome to C Programming);
Program:
#include<stdio.h>
#incude<conio.h>
Void main()
{
printf(Welcome to C Programming);
}
clrscr():- It clears text mode window.
Syntax:- void clrscr();
getch():- It gets a character from console but does not echo to the screen.
Syntax:- int getch();
Program:
#include<stdio.h>
#inculde<conio.h>
void main()
{
clrscr();
printf(WELCOME TO C PROGRAMMING);
getch();
}
C TOKENS
The smallest individual units or elements in a program are
called tokens. C has the following tokens
1. Identifiers
2. Keywords
3. Constants
4. Operators
5. Special characters.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
break
Continue
Far
Int
Short
Struct
Unsigned
Double
case
default
for
long
signed
switch
void
else
char
extern
goto
register
sizeof
typedef
while
enum
Numeric Constants
Character constants
Integer constants,
Real Constants
Constants, String Constants
Single Character
float:- The number which are stored in the form of floating point
representation is known as float data type. (or) The value with
decimal point./
Example: 11.53,153.2502,0.2345, etc.
double:- The number which are stored in the form of double
precision floating point representation is known as double data
type.
Example: 15325.437897, -2427.09987, 0.45972
USER DEFINED DATA TYPES
The user defined data types enable a program to invent his
own data types and define what values it can taken on.
Thus this data types can help a programmer to reducing the
programming errors. There are two types of user defined data
types namely..
1. enum
(enumerated data type)
2. typedef
(type definition)
DERIVED DATA TYPES
The derived data types are created from the basic integers,
characters and floating values. The examples of derived data types
are arrays, pointer, structures, unions, etc.,
Type Modifiers or Type Qualifiers
(signed, unsigned, short, long)
A type modifier alters the meaning of the base data type to
yield a new type. Each of these modifiers can be applied to the
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
base type int. The modifiers signed and unsigned can also be
applied to the base type char. In addition, long can applied to
double.
DATA TYPES, FORMAT SPECIFIERS, MEMORY SIZE
AND THEIR ACCESS ABILITY RANGE
S.NO. Data type
1.
7.
unsigned
char
Char
Int
unsigned
int
Long int or
long
unsigned
long
float
8.
double
%lf
9.
Long
double
Char[ ] or
%Lf
2.
3.
4.
5.
6.
10.
%c
%d
%u
1byte
2 bytes
2bytes
128 to 127
-32768 to 32767
0 to 65535
%ld
4 bytes
%lu
4bytes
-2147483648 to
2147483647
0 to 4294967295
%f
4bytes
%s
3.4*(10**-38) to
3.4*(10**+38) or
[-3.4e38 to +3.4e38]
8bytes
1.7*(10-308) to
1.7*(10**+308) or
[1.7e308to+1.7e308]
10 bytes 3.4*(10**-4932) to
1.1*(10**+4932)
--------
string
%x Hexa Decimal base
Address
%o Octal base
%p Memory
Variables:- A quantity which may vary during the execution of a program is known as variable.
Declaration of a variable:-
Examples:
int n;
char ch ;
float f;
int a,b,c;
Initialization:- At the time of declaring a variable we can store some data into that variable is known as
initialization.
data type identifier=value;
Examples:- int n=10;
char ch=s;
int a=10,b=20,c=30;
int a=100,b,c=150;
Example:int n=100;
1.printf(%d,n);
2.printf(value of n=%d,n);
output=100
output:- value of n=100
Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int n=10;
clrscr();
printf(Value of n=%d,n);
getch();
}
Program: Write a program to initialize 4 standard data type variables and display initial data.
#include<stdio.h>
#include<conio.h>
Void main()
{
int n=100;
char ch=h;
float f=158.0962;
double d=54932.2154;
clrscr();
printf(n=%d,n);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
printf(\n ch=%c,ch);
printf(\n f=%f,f);
printf(\n d=%lf,d);
getch();
}
Note:
1. In C language all declarations will be done before the first execution of programs.
2. Floating values displays 6 digits after the decimal point by default
Program:
#include<stdio.h>
#include<conio.h>
Void main()
{
float f=158.0962;
clrscr();
printf(f=%f,f);
printf(\n f=%.2f,f);
getch();
}
Escape sequence characters
\n = new line
\t = Horizontal tab (default 8 spaces)
\v = Vertical tab (default 1 line)
\b = Back space
\r = Carriage return
\a = Alert (Beep sound)
Program:
#include<stdio.h>
#inculde<conio.h>
void main()
{
clrscr();
printf(BDPS SOFTWARE LIMITED);
printf(\nVIJAYAWADA);
getch();
}
Constants:- Constants in C referred to fixed values that do not change during the execution of a program.
Const:- It is a keyword and is used to define constants.
Syntax:- const data type identifier=value;
(or)
Constdatatypeidentifier-1=value,identifier-2=value,identifier-n=value;
Program:
#include<stdio.h>
#inculde<conio.h>
void main()
{
const int n=100;
clrscr();
printf(n=%d\n,n);
/*n=200; cannot modify*/
Output:n=100
printf(n=%d,n);
n=100
getch();
}
Symbolic Constants:- It is a pre-processor statement and is used to define symbolic constants.
Syntax:#define identifier value.
Example:#define pi 3.14
#define g 9.8
Program
#include<stdio.h>
#inculde<conio.h>
#define pi 3.14
#define g 9.8
{
clrscr();
printf(pi=%.2f,pi);
printf(\n g=%.lf,g);
getch();
}
scanf():- It is a function, which is used to read data from standard input device.
Syntax:- int scanf(format(s),address-1,address-2,.,address-n);
Example:- int n ;
Address of n=&n
scanf(%d,&n);
Program
#include<stdio.h>
#inculde<conio.h>
void main()
{
int n;
clrscr();
prinf(Enter the value of n:);
scanf(%d,&n);
printf(Given value=%d,n);
getch();
}
Program
#include<stdio.h>
#inculde<conio.h>
void main()
{
char ch;
int n;
float f;
double d;
clrscr();
prinf(Enter any charactaer:);
scanf(%c,&ch);
prinf(Enter any value:);
scanf(%d,&n);
prinf(Enter any float:);
scanf(%f,&f);
prinf(Enter any double:);
scanf(%lf,&d);
printf(Given Characer=%c,ch);
printf(Given value=%d,n);
printf(Given float=%f,f);
printf(Given double=%lf,d);
getch();
}
Program
#include<stdio.h>
#inculde<conio.h>
void main()
{
int n;
char ch;
clrscr();
prinf(Enter any integer:);
scanf(%d,&n);
prinf(Enter any charactaer:);
scanf(%c,&ch);
printf(Given integer=%d,n);
printf(Given Characer=%c,ch);
getch();
}
In the above program it cannot read character into a character variable, because the int reading statement
creates a new line char in the input stream that will assign to the character variable.
To avoid this problem we use fflush function (or) \n character
fflush:- It flushed specified stream
Syntax:- int fflush (stream-name);
Example:-fflush(stdin);
flushall:- It flushes all open streams.
Syntax:- int flushall();
Program:
#include<stdio.h>
#inculde<conio.h>
void main()
{
int n;
char ch;
clrscr();
prinf(Enter any integer:);
scanf(%d,&n);
prinf(Enter any charactaer:);
scanf(%c,&ch);
fflush(stdin) or flushall ( );
printf(Given integer=%d,n);
printf(Given Character=%c,ch);
getch();
}
Program:
#include<stdio.h>
#inculde<conio.h>
void main( )
{
int n;
char ch;
clrscr();
prinf(Enter any integer:);
scanf(%d,&n);
prinf(Enter any charactaer:);
scanf(%\nc,&ch);
printf(Given integer=%d,n);
printf(Given Characer=%c,ch);
getch();
}
String:- A group of characters define between double quotation marks is a string.
In C language a string is nothing but an array of characters and terminated by a null character (\0).
Syntax:- char identifier[size];
Example:- char st(20);
Initialization:- char identifier= string;
Example:char st[20]= WELCOME;
Note:- When the compiler assigns a character string to a character array it automatically supplies a null
character(\0) at the end of the string.
Therefore the size should be equal to the maximum number of characters are string+1.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20];
clrscr();
OPERATORS
Definition:-It is a symbol which performs particular task. Ex:- +,-,*,etc....
Operand:- It is an entity which acts on operator.
Unary operators:- The operators consists only one operand are called unary operators.
Binary operators:- The operators consists two operands are called binary operators.
C has rich set of operators. They are
1. Arithmetic operators
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Bit-wise operators
6. Increment and decrement operators
7. Special operators
(i) ternary operator (or) Conditional operator
(ii) comma operator.
(iii) sizeof operator.
Arithmetical Operators:-These are the basic operators in C language. They are useful for performing
arithmetic calculations.
+ addition
/ division
- subtraction
% Modulus (remainder)
* Multiplication
Program:-Write a program to accept any two numbers and test all arithmetic operators
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter any Two numbers:");
scanf("%d%d",&a,&b);
printf("\nAddition of %d and %d is %d",a,b,a+b);
printf("\nSubtraction of %d and %d is %d",a,b,a-b);
printf("\nMultipliction of %d and %d is %d",a,b,a*b);
printf("\nDivision of %d and %d is %d",a,b,a/b);
printf("\nModulus of %d and %d is %d",a,b,a%b);
getch();
}
Logical operators:- These operators are used for combine the result of two or more expressions.
&&
Logical AND
||
Logical OR
!
Logical NOT
E1
T
T
F
F
E2
T
F
T
F
E1 && E2
T
F
F
F
E1 || E2
T
T
T
F
Relational operators:-These are used to test the relation between two values or two variables or expressions.
All c relational operators are binary operators and hence requires two operands.
<
less than
>
greater than
<=
less than or equal to
>=
greater than or equal to
==
equal to
!=
not equal to
Assignment operators:- These are used to assign a value of an expression to an identifier.
=
Assignment operator.
Compound assignment operators (or) Short hand assignment operators:-+=, -=, *=, /=, %=
Example:-int a=10;
a=a+20; (or) a+=20;
Increment and Decrement operators:- These are used to control the loops in an effective method.
Increment operators:- The symbol '++' is used for incrementing by 1.
Syntax:++identifier;
(prefix increment)
identifier++;
(postfix increment)
Example:- int a=10,b;
b=a++
here o/p : a=11,b=10
b=++a
here o/p : a=11,b=11
Decrement operators:- The symbol '--' is used for decrementing by 1.
Syntax:--identifier;
(prefix decrement)
identifier--;
(postfix decrement)
Example:- int a=10,b;
b=a-here o/p : a=9,b=10
b=--a
here o/p : a=9,b=9
BIT-WISE operators:- These are used for manipulating data at bit level they are two types:
1. Bitwise logical operators.
2. Bitwise shift operators.
Bit wise logical operators:-These are used for the bitwise logical decision making.
&
bitwise AND
|
bitwise OR
^ bitwise exclusive OR
E1
1
1
0
0
E2
1
0
1
0
E1 & E2
1
0
0
0
E1 | E2
1
1
1
0
E1 ^ E2
0
1
1
0
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
printf("\na&b=%d",a&b);
printf("\na|b=%d",a|b);
printf("\na^b=%d",a^b);
getch();
}
Bitwise shift operators:-The shift operators take binary patterns and shift the bits to the left or right.
<< - left shift
>> - right shift
Program:- To find b, c values using shift operators.
#include<stdio.h>
#include<conio.hsss>
void main()
{
int a=8,b,c;
clrscr();
b=a<<4;
c=a>>3;
printf("\n a=%d", a);
printf("\n b=%d", b);
printf("\n c=%d", c);
getch();
SPECIAL OPERATORS:
a) Ternary operator (or) Condition operator:-A Ternary operator is represented as "?:" It is used to construct
a conditional expression. The general form of ternary operator is exp1?exp2:exp3; here exp1 , exp2 , exp3 are
expressions.
If exp1 is true, then exp2 is evaluated and its value becomes the value of expression. If exp1 is false,
then the exp3 is evaluated and its value becomes the value of the expression.
Program:- Write a program to find max and min of given two values by using ternary operaotrs
#include<stdio.h>
#include<conio.h>
Example: int a=10,b=20,c,d;
void main()
c=a>b?a:b;
{
a=10, b=20 and c=20,d=10
int a,b,max,min;
clrscr();
printf("Enter values for a,b:");
scanf("%d%d",&a,&b);
max=a>b ? a:b;
min=a<b ? a:b;
printf("Maximum value is :%d",max);
printf("\nMinimum value is :%d",min);
getch();
}
b)Comma operator:-It can be used to link the relative expressions together. The general form of a comma
operator is
Syntax: identifier =(identifier1=value,---------identifier n=value, expression)
Program:#include<stdio.h>
Example: int a,b,c;
#include<conio.h>
c=(a=10,b=20,a+b);
void main()
Therefore a=10, b=20 , c=30
{
(first assigns the value 10 to a next assigns
int a,b,c;
the value 20 to b and finally assigns
clrscr();
the value 30 to c)
c=(a=10,b=20,a+b);
printf("a=%d",a);
printf("\nb=%d",b);
printf("\nc=%d",c);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
c=(a=10,b=20,(a+b)*2);
printf("\n a=%d",a);
printf("\n b=%d",b);
printf("\n c=%d",c);
getch();
}
c) sizeof operator:- It is a compile name operator and is used to get the memory size of a variable , expression
and data type.
Syntax:- sizeof(variable(or)exp(or)datatype);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
int n;
float ft;
double db;
clrscr();
printf("\nSize of char:%d byte",sizeof (ch));
printf("\nSize of int:%d byte",sizeof (n));
printf("\nSize of float:%d byte",sizeof (ft));
printf("\nSize of double:%d byte",sizeof (db));
getch();
}
Program:- Write a program to find maximum of given three values by using ternary operators.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
max=(a>b&&a>c)?a:(b>c?b:c);
printf("Maximum value=%d",max);
getch();
}
Program:-Write a program to find out the given value is even or Odd number by using ternary operators.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter any number:");
scanf("%d",&a);
a%2= =0? printf("Given number is even"):printf("Given number is odd");
getch();
}
Program:- Write a program to accept any two values and swapping the given values
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,t;
clrscr();
printf("Enter any two values into a and b:");
scanf("%d%d",&a,&b);
printf("Given values before swapping:");
printf("\na=%d",&a);
printf("\nb=%d",&b);
t=a;
a=b;
b=t;
printf("After Swapping:");
printf("\na=%d",&a);
printf("\nb=%d",&b);
getch();
}
Program:- Write same program without using third variable
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter any two values into a and b:");
scanf("%d%d",&a,&b);
printf("Given values before swapping:");
printf("\na=%d",&a);
printf("\nb=%d",&b);
/* AFTER SWAPPING*/
a=a+b;
b=a-b;
a=a-b;
printf("After Swapping:");
printf("\na=%d",&a);
printf("\nb=%d",&b);
getch();
}
PRECIDIENCE OF OPERATORS
S.No
1
Category
Highest
Unary
Multiplicative
Additive
Shift
Operator
()
[]
!
+
++
-&
sizeof
What it is or does
Function call
Array subscript
Logical negation
Unary plus
Unary minus
Increment operator
Decrement operator
Address
(returning size of
operand, in bytes)
*
/
%
+
<<
Mulitiply
Division
Remainder(modulus)
Binary Plus
Binary minus
Left shift operator
Relational
Equality
8
9
Conditional
Assignment
10
Comma
>>
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
=
*=
/+
%=
+=
-=
CONTROL STATEMENTS
(OR)
CONTROL STRUCTURES
C is consider as a structure programming language. One of the reason for this is having various program
control structures.
C process the decision making capabilities and supports the statements known as control statements.
There are 3 types of control statements supported by C
1. Condition control statements
2. Un condition control statements
3. Loop control statements.
1. Condition control statements:- C supports five types of condition control statements.
Simple if statement
If else statement
Nested if statement
Else if ladder
Switch statement
i) Simple if statement:- It is a decision making statements and is used to control the flow of execution.
Syntax:- if(expression)
Entry
{
Statements;
False
Ex
pr.
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
True
Statements
Next Statements
If expression is true then the statement block will be executed and the statement block will be executed
and the control transfer to the next statement. Otherwise the expression is false then the control directly go to
the next statement.
Program: Write a program to find max of two values by using simple if statement?
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
max=a;
if(max<b)
{
max=b;
}
printf("Max value:%d",max);
getch();
}
Note:- In any control statement the statement block contains only a single statement, braces are not necessary.
Program: Write a program to find the max value of given three numbers using simple if statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
max=a;
if(max<b)
max=b;
if(max<c)
max=c;
printf("Max value:%d",max);
getch();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
}
Program: Write a program to enter any date in date format and display given date.
#include<stdio.h>
#include<conio.h>
void main()
{
int d,m,y;
clrscr();
printf("Enter any date (dd-mm-yyyy):");
scanf("%d-%d-%d",&d,&m,&y);
printf("Given date:%.2d-%.2d-%d",d,m,y);
getch();
}
Program: Write a program to enter current date and date of birth. Calculate and display
#include<stdio.h>
#include<conio.h>
void main()
{
int d,m,y,cd,cm,cy,bd,bm,by;
clrscr();
printf("Enter current date (dd-mm-yyyy):");
scanf("%d-%d-%d",&cd,&cm,&cy);
printf("Enter Birth date (dd-mm-yyyy):");
scanf("%d-%d-%d",&bd,&bm,&by);
y=cy-by;
m=cm-bm;
d=cd-bd;
if(d<0)
{
d=d+30;
m=m-1;
}
if(m<0)
{
m=m+12;
y=y-1;
}
printf("Age is %dyear %dmonths %d days",y,m,d);
getch();
}
ii) If else statements:- It is an extension of simple if statement.
Syntax:- if(expression)
{
statement-1;
}
else
{
Statement-2;
}
Entry
False
Exp
r.
True
Statement 1
Statement 2
Next Statements
If the expression is true then if block statements are executed and else block statements are ignored.
Otherwise the expression is false, then else block statements are executed and if block statements are ignored.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
if(a<b)
max=a;
else
max=b;
printf("Max value:%d",max);
getch();
}
Program: Write a program to check whether the given no. is even or odd.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
if(n%2==0)
printf("Given number is even");
else
printf("Given number is odd");
getch();
}
iii) Nested if statement:- Using a if statement within another if is called nested if statement. If a series of
decisions are involved we use nested if statement.
Syntax:- if(expression-1)
{
If(expression-2)
{
----------------------{
Statements;
}
}
}
Syntax-2
if(expression-1)
{
if(expression-2)
{
statements-1;
}
else
{
statements-2;
}
}
else
{
if(expression-3)
{
statements-3;
}
else
{
statements-4;
}
}
Program: Write a program to find the maximum value of given 3 no's using nested if.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
max=a;
else
max=c;
}
else
{
if(b>c)
max=b;
else
max=c;
}
printf("Max Value for given 3 numbers:%d",max);
getch();
}
Program: Write a program to accept any character and check whether the given character is alphabet or digit
or a special character.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
scanf("%c",&ch);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
printf("Given character is alphabet");
else if(ch>=48 && ch<=57)
printf("Given character is digit");
else
printf("Given character is a special character");
getch();
}
Program: Write a program to accept any character and check whether the given character is vowel or
consonant or not an alphabet.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
scanf("%c",&ch);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
{
if(ch=='A' || ch=='a' || ch=='E'|| ch=='e' || ch=='I' || ch=='i' || ch=='O' || ch=='o' || ch=='U' || ch=='u')
printf("Given character is vowel");
else
printf("Given character is consonent");
}
else
printf("Given character is not a alphabet");
getch();
}
Program: Write a program to enter student number, student name, enter the marks in c, Cpp and unix.
Calculate and display total marks, average, result and division.
#include<stdio.h>
#include<conio.h>
void main()
{
int sno,c,cpp,unix,tot;
char sname[20],div,res;
float avg;
clrscr();
printf("Enter student number:");
scanf("%d",&sno);
printf("Enter student name:");
fflush(stdin);
gets(sname);
printf("Enter marks in c, cpp and unix:");
scanf("%d%d%d",&c,&cpp,&unix);
tot=c+cpp+unix;
avg=(float)tot/3;
clrscr();
printf("\nStudent number:%d",sno);
printf("\nStudent name:%s",sname);
printf("\nMarks in c:%d",c);
printf("\nMarks in cpp:%d",cpp);
printf("\nMarks in unix:%d",unix);
printf("\nTotal Marks:%d",tot);
printf("\nAverage:%d",avg);
if(c>=50 && cpp>=50 && unix>=50)
{
printf("\n Result
:Pass");
if(avg>=60)
printf("\n Division
:First");
else
printf("\n Division
:Second");
}
else
printf("\n Result
:Fail");
getch();
}
iv) else if ladder:- It is also used for a serried of decisions are involved.
Syntax:-if(expression-1)
{
stataement-1;
}
else if (expression-2)
{
statements-2;
}
---------------------------------------else if (expression-n)
{
statements-n;
}
else
{
statements;
}
In this statement expression are evaluated top to bottom. If the condition true, the statements associated
that blocks is executed and the control transfer to the next statement. When all expressions are false, then the
final else block statements will be executed.
Program: Write a program to find the maximum value of given 3 no's using nested if.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
#include<conio.h>
void main()
{
int cno,pmr,lmr,tu;
char cname[20];
float bill;
clrscr();
printf("Enter consumer number:");
scanf("%d",&cno);
printf("Enter consumer name:");
fflush(stdin);
gets(cname);
printf("Enter pmr and lmr:");
scanf("%d%d",&pmr,&lmr);
tu=pmr-lmr;
if (tu<=50)
bill=(50*1.25);
if (tu<=100)
bill=(50*1.25)+((tu-50)*2.10);
if (tu<=200)
bill=(50*1.25)+(50*2.10)+((tu-100)*2.85);
if (tu<=400)
bill=(50*1.25)+(50*2.10)+(100*2.85)+((tu-200)*3.50);
else
bill=(50*1.25)+(50*2.10)+(100*2.85)+(200*3.50)+((tu-400)*4.50);
clrscr();
printf("\nConsumer number
:%d",cno);
printf("\nConsumer name
:%s",cname);
printf("\nPresent month reading
:%d",pmr);
printf("\nLast month reading
:%d",lmr);
printf("\nTotal units
:%d",tu);
printf("\nBill amount
:%.2f",bill);
getch();
}
*Exit:- It terminated the program header file process.H
Syntax:- void exit(int status);
*Status:- Typically a value of 0 indicates a normal exit, and a non zero value indicates some error.
Program: Write a program to enter dealer number, dealer name, dealer region, number of liters petrol sold, no.
of liters diesel sold, no. of liters kerosene sold.
Dealer region are N- north, E-east, W-west, S-south
Calculate and display total region collection by the following table.
Petrol
Diesel
Kerosene
North
49.75
32.65
18.95
South
49.25
32.15
18.25
East
48.95
31.75
17.50
West
48.35
30.85
17.35
#include<stdio.h>
#include<conio.h>
void main()
{
int dno,nps,nds,nks;
char dname[20],dregion[20];
float trgc,tcn,tcs,tce,tcw;
clrscr();
printf("Enter dealer number:");
scanf("%d",&dno);
printf("Enter dealer name:");
fflush(stdin);
gets(dname);
printf("Enter no of litres petrol sold:");
scanf("%d",&nps);
printf("Enter no of litres Kerosene sold:");
scanf("%d",&nks);
printf("Enter no of litres diesel sold:");
scanf("%d",&nds);
tcn=nps*49.75+nds*32.65+nks*18.95;
tcs=nps*49.25+nds*32.15+nks*18.25;
tce=nps*48.95+nds*31.75+nks*17.50;
tcw=nps*48.35+nds*30.85+nks*17.35;
trgc=tcn+tce+tcs+tcw;
clrscr();
printf("\ntotal collection in north
:%.2f",tcn);
printf("\ntotal collection in east
:%.2f",tce);
printf("\ntotal collection in West
:%.2f",tcw);
printf("\ntotal collection in South
:%.2f",tcs);
printf("\ntotal region class
:%.2f",trgc);
getch();
}
II method:
#include<stdio.h>
#include<conio.h>
void main()
{
int dno,np,nd,nk;
char dname[20],reg;
float pa,da,ka,ta;
clrscr();
printf("Enter dealer number:");
scanf("%d",&dno);
printf("Enter dealer name:");
fflush(stdin);
gets(dname);
printf("Enter dealer region:");
scanf("%c",®);
if(reg!='N' && reg!='S' && reg!='W' && reg!='E')
{
printf("Invalid region:");
getch();
exit(0);
}
printf("Enter no of lts petrol sold:");
scanf("%d",&np);
printf("Enter no of lts diesel sold:");
scanf("%d",&nd);
printf("Enter no of lts kerosene sold:");
scanf("%d",&nk);
if (reg=='N')
{
pa=np*49.75;
da=nd*32.65;
ka=nk*18.95;
}
else if (reg=='S')
{
pa=np*49.25;
da=nd*32.15;
ka=nk*18.25;
}
else if (reg=='E')
{
pa=np*48.95;
da=nd*31.75;
ka=nk*17.50;
}
else
{
pa=np*48.35;
da=nd*30.85;
ka=nk*17.35;
}
ta=pa+da+ka;
clrscr();
printf("\n Dealer number
:%d",dno);
printf("\n Dealer name
:%s",dname);
{
printf("Invalid grade");
getch();
exit(0);
}
printf("Enter basic salary:");
scanf("%f",&bs);
if(gr=='A' || gr=='a')
{
if(bs<=2000)
{
hra=bs*8/100;
da=bs*12/100;
ta=bs*2/100;
it=0;
pf=bs*2/100;
}
else if(bs<=4000)
{
hra=bs*10/100;
da=bs*14/100;
ta=bs*3/100;
it=bs*2/100;
pf=bs*4/100;
}
else if(bs<=5000)
{
hra=bs*12/100;
da=bs*15/100;
ta=bs*4/100;
it=bs*4/100;
pf=bs*6/100;
}
else
{
hra=bs*14/100;
da=bs*18/100;
ta=bs*5/100;
it=6/100;
pf=bs*8/100;
}
}
else
{
if(bs<=2000)
{
hra=bs*6/100;
da=bs*8/100;
ta=bs*1/100;
it=0;
pf=bs*1/100;
}
if(bs<=4000)
{
hra=bs*8/100;
da=bs*10/100;
ta=bs*3/100;
it=bs*2/100;
pf=bs*2/100;
}
else
{
hra=bs*10/100;
da=bs*14/100;
ta=bs*5/100;
it=bs*3/100;
pf=bs*4/100;
}
}
gs=bs+hra+da+ta;
ded=it+pf;
ns=gs-ded;
clrscr();
printf("\nEnter Employee numbe:%d",eno);
printf("\nEnter Employee name :%s",ename);
printf("\nEnter Employee grade:%c",gr);
printf("\nBasic Salary
:%.2f",bs);
printf("\nHra
:%.2f",hra);
printf("\nDa
:%.2f",da);
printf("\nta
:%.2f",ta);
printf("\nit
:%.2f",it);
printf("\npf
:%.2f",pf);
printf("\nGross Salary
:%.2f",gs);
printf("\nDeductions
:%.2f",ded);
printf("\nNet Salary
:%.2f",ns);
getch();
}
v) Switch Statement:- It is a multi way conditional statement used in c language. It is mainly used in situations
where there is need to pick one alternate among many alternates.
Syntax:Switch (expression or variable)
{
Case value 1;
Statement1;
Break;
------------------------------------------Case value n;
Statements n;
Break.;
Default;
Default statement;
}
The switch statement tests the value of the given variable or expression against a list of case values and
when a match is found, a block of statements associated that case is executed. Otherwise the default block
statements will be executed.
Break:- It is unconditional control statement and is used to terminate a switch statement.
Syntax :- break;
Note:- i) In switch statement the variable or expression is an integral value.(int & char).
ii) It cannot pass string and floating values.
iii) In switch statement the default block is optional.
Program: Write a program to test all arithmetic operations using switch statement
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,opt;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Enter Option");
scanf("%d",&opt);
switch(opt)
{
case1 :
printf("\nAddition %d and %d is %d",a,b,a+b);
break;
case2 :
printf("\nSubtraction %d and %d is %d",a,b,a-b);
break;
case3 :
printf("\nMultiplication %d and %d is %d",a,b,a*b);
break;
case4 :
printf("\nDivision %d and %d is %d",a,b,a-b);
break;
case5 :
printf("\nModulus %d and %d is %d",a,b,a%b);
break;
default :
printf("\nInvalid Region:");
}
getch();
}
Program: Write a menu driven program to compute the electricity bill for the domestic and commercial
purposes with the following data.
For Domestic purpose:
units
Rate/unit
-------------------------0-50
1.45
51-100
2.85
101-200
3.95
201-300
4.50
201-300
5.00
-------------------------extras: Rs.10/- Service charge and Rs.0.06 ps per unit power tax, Subject to
minimum of Rs.10 single phase and Rs.20 for 3 phase
For Commercial purpose
units
Rate/Unit
----------------------------0-100
3.95
above 100
7.00
---------------------------extras: Rs.20/- Service charge and Rs.0.06 ps per unit power tax, Subject to
minimum of Rs.20 single phase and Rs.50 for 3 phase
#include<stdio.h>
#include<conio.h>
void main()
{
int cno, pmr,lmr,tu,ph;
char cname[20],type;
float bill,se, pt,tamt;
clrscr();
printf("\n\t\tMENU");
printf("\n\t\t---------------");
printf("\n\t\tCOMMERCIAL(C\c)");
printf("\n\t\tDOMESTIC(D/d)");
printf("\n\t\t---------------");
printf("\n\t\tEnter your option:");
scanf("%c",&type);
if(type!='C' && type!='c' && type!='D' && type!='d')
{
printf("\n\t\tInvalid Type:");
getch();
exit(0);
}
printf("\n\tEnter phase type (1 or 3):");
scanf("%d",&ph);
if(ph!=1 && ph!=3)
{
printf("\n\t Invalid phase");
getch();
exit(0);
}
clrscr();
printf("Enter consumer number:");
scanf("%d",&cno);
printf("Enter consumer name:");
fflush(stdin);
gets(cname);
printf("Enter pmr and lmr:");
scanf("%d%d",&pmr,&lmr);
tu=pmr-lmr;
switch(type)
{
case 'd':
case 'D':
if(tu<=50)
bill=(50*1.45);
else if(tu<=100)
bill=(50*1.45)+(tu-50)*2.85;
else if(tu<=200)
bill=(50*1.45)+(50*2.85)+(tu-100)*3.95;
else if (tu<=300)
bill=(50*1.45)+(50*2.85)+(100*3.95)+(tu-200)*4.50;
else
bill=(50*1.45)+(50*2.85)+(100*3.95)+(200*4.50)+(tu-300)*5.00;
se=10.00;
pt=tu*0.06;
if(ph==1)
{
if(pt<10.00)
pt=10.00;
}
else
{
if(pt<20.00)
pt=20.00;
}
break;
case 'c':
case 'C':
if(tu<=100)
bill=(100*3.95);
else
bill=(100*3.95)+(tu-100)*7.00;
se=20.00;
pt=tu*0.06;
if(ph==1)
{
if(pt<20.00)
pt=20.00;
}
else
{
if(pt<50.00)
pt=50.00;
}
break;
}
tamt=bill+se+pt;
clrscr();
printf("\nConsumer Number
:%d",cno);
printf("\nConsumer name
:%s",cname);
printf("\nType(c-com,d-dom)
:%c",type);
printf("\nphase
:%d",ph);
printf("\nPresent Month Reading
:%d",pmr);
printf("\nLast Month Reading
:%d",lmr);
printf("\nTotal Units
:%d",tu);
printf("\nBill Amount
:%.2f",bill);
printf("\nService Charges
:%.2f",se);
printf("\nPower tax
:%.2f",pt);
printf("\nTotal Amount
:%.2f",tamt);
getch();
}
UNCONDITIONAL CONTROL STATEMENT
1. Break (key word):- The break statement causes control to pass to the statement following the innermost
enclosing while, do, for, or switch statement.
Syntax:- break;
(Passes control)
2. Continue (key word):- The continue statement causes control to pass to the end o the innermost enclosing
while, do or for statement, at which point the loop continuation condition in re-evaluated.
Syntax:- continue;
(Passes control)
3. Goto:- The goto statement is an unconditional control statement which is used up the execution of program
sequence by transfer of control to the some other part of the program.
Syntax:- goto label;
Where label is C valid identifier used to the label of the destination such that the control could
transferred label.
Syntax:- identifier;
Program: Write a program to display natural numbers from one to given natural numbers using goto
statement.
#include<stdio.h>
#include<conio.h>
int n,i=1;
clrscr();
printf(Enter any number:);
scanf(%d,&n);
lb:
printf(Natural numbers from 1 to %d,n);
printf(%d\t,i);
i++;
if(i<=n)
goto lb;
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
int n;
clrscr();
printf(Enter any number:);
scanf(%d,&n);
if(n= =1)
gotot lb1;
if(n= =2)
goto lb2;
printf(WECOME\n);
lb1:
printf(Label 1\n);
lb2:
printf(Label 2\n);
getch();
}
<Dos.H>
Delay: Suspends execution for interval (milli seconds)
Declaration:- void delay (unsigned milli seconds);
<conio.h>
Gotoxy:-It is used to move the cursor to specify the location is text window.
Syntax:- void gotoxy(intx, inty);
Program:
#include<stdio.h>
#inculde<conio.h>
void main()
{
clrscr();
gotoxy(70,25);
printf(WELCOME);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sno,c,cpp,java,tot,sc=23,ec=57,i;
char sname[20],ch;
float avg;
_setcursortype(2);
do
{
clrscr();
gotoxy(24,5);
printf("---------------------------------");
gotoxy(30,6);
printf("BDPS SOFTWARE LIMITED");
gotoxy(35,7);
printf("VIJAYAWADA");
gotoxy(24,8);
printf("---------------------------------");
gotoxy(23,5);
printf("%c",'');
gotoxy(57,5);
printf("%c",'');
gotoxy(57,22);
printf("%c",'');
gotoxy(23,22);
printf("%c",'');
for(i=6;i<=21;i++)
{
gotoxy(sc,i);
printf("%c",'');
}
for(i=6;i<=21;i++)
{
gotoxy(ec,i);
printf("%c",'');
}
gotoxy(24,9);
printf("SNO :");
//31
gotoxy(24,11);
printf("SNAME :");
gotoxy(24,13);
printf("MARKS IN C
:");
// 39
gotoxy(24,15);
printf("MARKS IN CPP :");
gotoxy(24,17);
printf("MARKS IN JAVA :");
gotoxy(33,19);
printf("TOTAL :");
gotoxy(33,21);
printf("AVERAGE :");
gotoxy(24,22);
printf("---------------------------------");
gotoxy(32,9);
scanf("%d",&sno);
gotoxy(32,11);
fflush(stdin);
gets(sname);
gotoxy(45,13);
scanf("%d",&c);
gotoxy(45,15);
scanf("%d",&cpp);
gotoxy(45,17);
scanf("%d",&java);
tot = c + cpp + java;
avg = (float) tot/3;
gotoxy(45,19);
printf("%d",tot);
gotoxy(45,21);
printf("%.2f",avg);
gotoxy(24,23);
printf("Do you enter another record(y/n):");
fflush(stdin);
scanf("%c",&ch);
}while(ch!='n');
}
Loop:- The process of repeated executing a block of statements is called loop. C supports three types of looping
statements. They are
While Loop
Entry
do-while loop and
for-loop
False
Any loop has three things. They are
Test
1. Initialize the index
Conditi
on
2. Test condition
3. Update the index
True
Statements
1. while loop:- It is a conditional control loop statement in C language.
Syntax:- while(test condition)
{
Next Statements
Statements;
}
First the test condition is evaluated and if it is true then the statement block will be executed. After the
execution of statements the test condition is evaluated once again.
Then if it is true the statement block will be executed continuous until the test condition finally becomes false.
Program: Write a program to display natural numbers from 1 to given number using
'While Loop'
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Natural Numbers from 1 to %d:\n",n);
while (i<=n)
{
printf("%d\t",i);
i++;
}
getch();
}
Program: Write a program to check whether the given number is prime or not
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1,count=0;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
while(i<=n)
{
if(n%i==0)
count++;
i++;
}
if(count==2)
printf("Given no is prime");
else
printf("Given no is not prime");
getch();
}
Program: Write a program to accept any number and display reverse number(image no)
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
unsigned long rev=0;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
while(n>0)
{
rev=rev*10+(n%10);
n=n/10;
}
printf("Reverse number=%lu",rev);
getch();
}
Program: Write a program to accept any number and check whether the given number is palindrome number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,rev=0;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
m=n;
while(m>0)
{
rev=rev*10+(m%10);
m=m/10;
}
if(n==rev)
Program: Write a program to accept any number and display sum of digits in the given number
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long n;
int sum=0;
clrscr();
printf("Enter any number:");
scanf("%lu",&n);
while(n>0)
{
sum=sum+(n%10);
n=n/10;
//n=1234,n>0,
}
// sum=9+1,s=10,n=0
printf("Sum of digits in the given number:%d",sum);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Factors of %d:",n);
while(i<=n)
{
if(n%i==0)
printf("%d\t",i);
i++;
}
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Program: Write a program to display even numbers and odd numbers from 1 to given number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Even numbers from 1 to %d:",n);
while (i<=n)
{
if(i%2==0)
printf("%d\t",i);
i++;
}
i=1;
printf("\nOdd numbers from 1 to %d:",n);
while(i<=n)
{
if(i%2==1)
printf("%d\t",i);
i++;
}
getch();
}
else
printf("Given number is not Armstrong");
getch();
}
Program: Write a program to display even and odd no of 1 to given number using continue statement
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=0;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Even number from 1 to %d:\n",n);
while(i<n)
{
i++;
if(i%2==1)
continue;
printf("%d\t",i);
}
i=0;
printf("\nOdd numbers from 1 to %d\n",n);
while(i<=n)
{
i++;
if(i%2==0)
continue;
printf("%d\t",i);
}
getch();
}
Program: Calculate and display G.C.D of given two numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,g,m,i;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
m=a<b?a:b;
for(i=1;i<=m;i++)
{
if(a%i==0 && b%i==0)
g=i;
}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Program: Method 1
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long n;
int sum=0;
clrscr();
printf("Enter any number:");
scanf("%lu",&n);
while(n>0)
{
sum=sum+(n%10);
n=n/10;
if(n==0)
{
if(sum>9)
{
printf("%d\n",sum);
n=sum;
sum=0;
}
}
}
printf("Final sum is:%d",sum);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
getch();
}
Method-2
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long n;
int sum=0;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
sum=n%9;
if(sum==0)
printf("Sum is %d",9);
else
printf("Sum is %d",sum);
getch();
}
Program: Write a program to accept any decimal number and displays binary number
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
unsigned long bin=0,b=1;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
while(n>0)
{
bin=bin+(n%2)*b;
n=n/2;
b=b*10;
}
printf("Binary number of given decimal number:%lu",bin);
getch();
}
Program: Write a program to accept any binary number and display decimal number
#include<stdio.h>
#include<conio.h>
void main()
{
int n=0,b=1,r;
unsigned long bia;
clrscr();
printf("Enter any binary number:");
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
scanf("%lu",&bia);
while(bia>0)
{
r=bia%10;
if(r!=1 && r!=0)
{
printf("Invalid binary number:");
getch();
exit(0);
}
n=n+r*b;
bia=bia/10;
b=b*2;
}
printf("Decimal number of given binary number :%d",n);
getch();
}
2. do-while loop:- It is an alternative form of while loop. The only difference between while and do while is
the minimum number of execution of while is 0. For minimum no of execution of do-while is 1.
Syntax:- do
{
Statements;
}
While(test condition);
Flowchart
Entry
Statements
Test
conditon
True
Next Statements
First the statement block will be executed and then test condition will be evaluated. If the condition is
true then the statement block will be executed once again. This process of repeated executed continuous until
the test condition finally becomes false
Program: Write a program to accept and display natural numbers, from one to given number using do-while
loop
#include<stdio.h>
#include<conio.h>
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
void main()
{
int n,i=1;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Natural numbers form 1 to %d:\n",n);
do
{
printf("%d\t",i);
i++;
}
while(i<=n);
getch();
}
3. for loop:- It is the most commonly used loop statement in C language. It consisting of three expressions.
Syntax:- for(exp1; exp2; exp3)
{
Statements;
}
The first expression is used to the initialize the index, second expression is used to check whether the
loop is to be continued or not, third expression is used to change the index for further iteration (increment or
decrement).
Entry
Initialize the Index
False
Test
Condition
Expression
2
True
Next Statements
Statements
Program: Write a program to accept any number and check whether the given number is perfect or not.
*sum of factors except that number is called perfect number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("Given number is perfect");
else
printf("Given number is not pefect ");
getch();
}
_setcursortype:- It selects cursor appearance
Syntax:- void_setcursor type(int cur_t);
Types of cursors:1. _nocursor (turns off the cursor)
2. _solidcursor (solid block cursor)
3. _normalcursor (normal under scroll cursor)
Kbhit:- It checks for currently available key strokes.
Syntax:- int kbhit();
Nested loops:- Using a loop statement within another loop is called Nested loop.
Program: Write a program to display palindrome numbers from 1 to given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,rev;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Palindrome number from 1 to %d:\n",n);
for(i=1;i<=n;i++)
{
m=i;
rev=0;
while(m>0)
{
rev=rev*10+(m%10);
m=m/10;
}
if(rev==i)
printf("%d\t",i);
}
getch();
}
Program: Write a program to display prime numbers from 1 to given numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,c;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Prime Numbers from 1 to %d:",n);
for(i=1;i<=n;i++)
{
c=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
c=c++;
}
if(c==2)
printf("%d\t",i);
}
getch();
}
Program: Write a program to display perfect numbers from 1 to given numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,j,i,sum;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Perfect number from 1 to %d:\t",n);
for(i=1;i<=n;i++)
{
sum=0;
for(j=1;j<=i/2;j++)
{
if(i%j==0)
sum=sum+j;
}
if(sum==i)
printf("%d\t",i);
}
getch();
}
Program: Write a program to display Armstrong numbers from 1 to given numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,r,sum;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
printf("Armstrong numbers from 1 to %d:",n);
for(i=1;i<=n;i++)
{
m=i;
sum=0;
while(m>0)
{
r=m%10;
sum=sum+(r*r*r);
m=m/10;
}
if(sum==i)
printf("%d\t",i);
}
getch();
}
Program: Write a program to accept any number calculate and display square root of a given number without
using library functions.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
float j;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
i=1;
while(i*i < n)
{
i++;
}
if(i*i == n)
printf("Square root of given number is %d",i);
else
{
j=i-1;
while(j*j<n)
{
j=j+0.00001;
}
printf("Square root of given number:%.3f",j);
}
getch();
}
Program: Write a program to enter base and power calculate and display exponent ional value.
#include<stdio.h>
#include<conio.h>
void main()
{
int b,p,i;
float e=1;
clrscr();
printf("Enter base and power:");
scanf("%d%d",&b,&p);
if(p>0)
{
for(i=1;i<=p;i++)
{
e=e*b;
}
}
if(p<0)
{
for(i=p;i<0;i++)
{
e=e*1/b;
}
}
printf("Exponential of %d and %d is :%.3f",b,p,e);
getch();
}
printf(%5d,n);
or
printf(%-6d,n);
o/p:100
o/p:--100 (2spaces)
o/p:100--- (3 spaces)
Char ch=H;
Printf(%c,ch);
printf(%3c,ch);
printf(%-5c,ch);
o/p:H
o/p:--H (2spaces)
float ft=123.734;
Printf(%f,ft);
o/p:123.734000
printf(%12f,ft);
o/p:--123.734000 (2spaces)
printf(%.2f,ft);
o/p: 123.73
Char:-
Float:-
printf(%8.2f,ft); o/p:--123.73
String:string st= WELCOME;
printf(%s,st);
o/pWELCOME
printf(%9s,st);
o/p--WELCOME(2spaces)
printf(%.3s,st);
o/pWEL
int n=3
pirntf(%.*s,n,st);
o/p:WEL
Program: Write a program to generate the following pattern
W
WE
WEL
WELC
WELCO
WELCOM
WELCOME
#include<stdio.h>
#include<conio.h>
void main()
{
char st[10]="WELCOME";
int i;
clrscr();
for(i=1;i<=7;i++)
{
printf("\n%.*s",i,st);
}
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=20;i++)
{
printf("\n%d%3c%3d%3c%4d",n,'*',i,'=',n*i);
}
getch();
}
Program: Write a program to enter any number and display mathematical table from one to given
numbers(each screen contains 3 tables)
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,r=1,c=1;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
clrscr();
for(i=1;i<=n;i++)
{
for(j=1;j<=20;j++)
{
gotoxy(c,r);
printf("%d%3c%3d%3c%4d",i,'*',j,'=',i*j);
r++;
}
if(r>20)
{
r=1;
c=c+28;
}
if(i%3==0)
{
printf("\n\nPress any key to continue....");
getch();
clrscr();
c=1;
r=1;
}
}
getch();
}
Program: Write a program to generate the following pattern
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%3c",'*');
}
printf("\n\n");
}
getch();
}
Program: Write a program to generate the following pattern
*****
*****
*****
*****
*****
1
22
333
4444
55555
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%3d",i);
}
printf("\n\n");
}
getch();
}
Program: Write a program to generate there following pattern
1
12
123
1234
12345
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%3d",j);
}
printf("\n\n");
}
getch();
}
Program: Write a program to generate the following pattern
*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,s;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
s=n*2;
for(i=1;i<=n;i++)
{
printf("%c",s,32);
for(j=1;j<=i;j++)
{
printf("%4c",'*');
}
printf("\n");
s=s-2;
}
getch();
}
Program: Write a program to generate the Pascal triangle of n rows using functions
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int n,ncr,i,j,s;
clrscr();
printf("Enter any value into n:");
scanf("%d",&n);
s=n*3;
for(i=0;i<=n;i++)
{
printf("%*c",s,32);
for(j=0;j<=i;j++)
{
ncr=fact(i)/fact(j)*fact(i-j);
printf("%6d",ncr);
}
printf("\n");
s=s-3;
}
getch();
}
unsigned long fact(int x)
{
unsigned long f=1;
int i;
for(i=1;i<=x;i++)
{
f=f*i;
}
return f;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,j,k,s=2;
clrscr();
printf("Enter any number into n:");
scanf("%d",&n);
clrscr();
for(i=n;i>=1;i--)
{
k=i;
printf("%*c",s,32);
for(j=1;j<2*i;j++)
{
printf("%2d",k);
if(j<i)
k--;
else
k++;
}
printf("\n");
s=s+2;
}
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k=1;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%3d",k);
if(j<n)
{
if(i%2==0)
k--;
else
}
}
}
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,j,k,s;
clrscr();
printf("Enter any value into n:");
scanf("%d",&n);
s=2*n;
m=1;
for(i=1;i<2*n;i++)
{
k=1;
printf("%*c",s,32);
for(j=1;j<2*m;j++)
{
}
}
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,j,k,s=2;
clrscr();
printf("Enter any vlaue of n:");
scanf("%d",&n);
m=n;
for(i=1;i<2*n;i++)
{
k=m;
printf("%*c",s,32);
for(j=1;j<2*m;j++)
{
printf("%2d",k);
if(j<m)
k--;
else
k++;
}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
printf("\n");
if(i<n)
{
s=s+2;
m--;
}
else
{
s=s-2;
m++;
}
}
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,p,x=7,y=7;
clrscr();
textcolor(14+BLINK);
for(i=1;i<=13;i++)
{
p=65;
for(j=1;j<=13;j++)
{
if(i>1 && (j>=x && j<=y))
cprintf("%2c",'*');
else
printf("%2c",p);
if(j<7)
p++;
else
p--;
}
printf("\n");
if(i>1)
{
if(i<7)
{
x--;
y++;
}
else
{
x++;
y--;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
}
}
}
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,p,x=7,y=7;
clrscr();
for(i=1;i<=7;i++)
{
p=65;
for(j=1;j<=13;j++)
{
if(i>1 && (j>=x && j<=y))
printf("%2c",32);
else
printf("%2c",p);
if(j<7)
p++;
else
p--;
}
printf("\n");
if(i>1)
{
x--;
y++;
}
}
getch();
}
Text Color:- It selects a new character color in textmode.
Declaration:- void textcolor(int new color);
Text Background:- It selects a new text background color.
Declaration:- void textbackground(int newcolor);
S.no.
Constant
Color(text mode)
Value
Background
Fore ground
1
BLACK
0
YES
YES
2
BLUE
1
YES
YES
3
GREEN
2
YES
YES
4
CYAN
3
YES
YES
5
RED
4
YES
YES
6
MAGENTA
5
YES
YES
7
BROWN
6
YES
YES
8
LIGHT GRAY
7
YES
YES
9
DARK GRAY
8
NO
YES
10 LIGHT BLUE
9
NO
YES
11 LIGHT GREEN
10
NO
YES
12
LIGHT CYAN
11
NO
YES
13 LIGHT RED
12
NO
YES
14 LIGHT MAGENTA
13
NO
YES
15 YELLOW
14
NO
YES
16 WHITE
15
NO
YES
17 BLINK
128
NO
***
*** To display blinking characters in text mode, add BLINK to the foreground color.
Textmode():-It Changes screen mode (in text mode)
Declaration: void textmode(int newmode);
Constant
LASTMODE
BW40
C40
BW80
C80
MONO
C4350
VGA
ValueText
-1
0
1
2
3
7
64
50-line
Mode
Previous text mode
Black and white
Color
Black and white
Color
Monochrome
EGA and
40 columns
40 columns
80 columns
80 columns
80 columns
43-line
cprintf:- It is same as printf if you want to display colors in text mode we use cprintf.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
textmode(1);
textcolor(RED+BLINK);
textbackground(WHITE);
gotoxy(16,12);
cprintf("WELCOME");
getch();
}
<DOS.H>
Delay: Suspends execution for interval (milli seconds)
Declaration: void delay (unsigned milliseconds);
kbhit:- It checks for currently available keystrokes.
Declaration: int kbhit();
DIGITAL CLOCK
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int h,m,s;
clrscr();
printf("Enter any time(hh:mm:ss):");
scanf("%d:%d:%d",&h,&m,&s);
textmode(0);
textcolor(RED);
_setcursortype(_NOCURSOR);
while(!kbhit())
{
clrscr();
gotoxy(15,12);
cprintf("%.2d:%.2d:%.2d",h,m,s);
delay(100);
s++;
if(s>59)
{
m++;
s=1;
}
if(m>59)
{
h++;
m=0;
}
if(h>12)
h=1;
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int c=1,c1=75,r=1;
textmode(2);
_setcursortype(0);
textcolor(RED);
while(!kbhit())
{
clrscr();
gotoxy(37,r);
cprintf("LOVES");
gotoxy(c,12);
cprintf("PRIYA");
gotoxy(c1,12);
cprintf("MADHU");
c=c+2;
c1=c1-2;
r=r+1;
if(c>75)
{
c=1;
c1=75;
}
if(r>25)
r=1;
delay(80);
}
}
*
**
***
****
*****
*****
*****
*****
*****
ARISE, AWAKE AND STOP TILL THE GOAL
* * * *IS
* NOT REACHED
1
22
333
4444
55555
FUNCTIONS
Function:- It is a self contained block of statements and it can be used at several multiple times in a program
but defined only once.
Library function or Predefined functions:- The functions which are in built with the C-compiler is called as
library functions. Ex:- printf, scanf, getch(), clrscr(); etc.,
User defined function:- User can defined functions to do a task relevant to their programs. Such functions are
called as user defined functions.
Any function has three things. They are
1. Function declaration
2. Function definition
3. Function calling.
In case of pre-defined functions the function declaration is in header files, definition is in C Libraries
and calling is in your source program.
But in case of user defined functions all the three things are in your source program.
Function declaration:Syntax:- Returntype func_name([Arg List]);
Example:-Void test();
Int sum(int , int );
Function definition:Syntax:- returntype func_name([Arg List])
{
Body;
}
Function calling:Syntax:- func_name([Arg List]);
The arguments which we given at the time of function declaration or definition are called arguments or
formal arguments.
The arguments which are given at the time of function calling are called actual arguments or
parameters.
void:- (Empty data type)
#include<stdio.h>
#include<conio.h>
void main()
{
void test( ); /*declaration*/
clrscr();
test( ); /*calling*/
getch();
}
void test() /*definition*/
{
printf(welcome to c functions:);
}
Rules for creating and accessing user defined functions:1. A function can be called by any number of times.
2. A function may or may not receive arguments.
3. A function may or may not return a value.
4. If a function does not return any value the function return data type will be specified as void
5. If a function returns a value only one value can be returned.
6. We cannot specify any return data type, the function returns on integer value by default.
7. The returning value must be return with a statement return.
8. If a function returns a value, the execution of return statement should be last
9. If a function returns a value, the returning value should match with the function return data type.
10. A function is executed when a function is call by its name.
11. Before a function call, function declaration or definition must and should
12. A function definition may be placed before or after the main function.
13. If a function call, function definition can be specified any where in the program
14. If a function definition is specified before the function called then the function declaration is not
necessary.
15. The function definition should not be terminated with semicolon( ; )
Return:- Exits immediately from the currently execution of function to the calling rotated optionally returning
a value.
Syntax:- return [<expression>];
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int,int);
int a,b,n;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
n=sum(a,b);
printf("Sum is %d",n);
getch();
}
int sum(int x,int y)
{
return x+y;
}
Function Prototypes and category of functions:
A Function depending and whether arguments are present or not and a value is returned or not, may
belong to one of the following categories.
/*declaration;*/
/*calling;*/
/* definition*/
printf("Sum is %d\n",x+y);
}
3.Function with arguments and return value:- In this type the function has some arguments. It receives data
from the calling function. Similarly it returns a value. The calling function receive data from the called
function. So it is a two way data communication between the calling function and the called function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int,int);
int a,b,n;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
n=sum(a,b);
printf("Sum is %d",n);
getch();
}
int sum(int x,int y)
{
return x+y;
}
4. Function with no arguments and return value:- In this type the function has no arguments. It does not
receive data from the calling function. But it returns a value the calling function receive data from the called
function. So it is a one way data communication between called function and the calling function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum();
/*declaration;*/
int s;
clrscr();
s=sum();
/*calling;*/
printf("Sum is %d",s);
getch();
}
int sum()
/* definition*/
{
int a,b;
printf("Enter any two values:");
scanf("%d%d",&a,&b);
return a+b;
}
Program: Write a program to display natural numbers from one to given number by using user defined
functions
#include<stdio.h>
#include<conio.h>
void main()
{
void disp(int);
int n;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
disp(n);
getch();
}
void disp(int x)
{
int i;
for(i=1;i<=x;i++)
printf("%d\t",i);
}
Program: Write a program to display factors of given number
#include<stdio.h>
#include<conio.h>
void main()
{
void disp(int);
int n;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
disp(n);
getch();
}
void disp(int x)
{
int i;
for(i=1;i<=x;i++)
{
if(x%i==0)
printf("%d\t",i);
}
}
Program: Write a program to calculate and display reverse number of given number.
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long revnum(int);
int n;
unsigned long r;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
r=revnum(n);
printf("reverse number is:%lu",r);
getch();
}
unsigned long revnum(int x)
while(x>0)
{
rev=rev*10+(x%10);
x=x/10;
}
return rev;
}
Program: Write a program to calculate factorial of given number
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int n;
unsigned long f;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
f=fact(n);
printf("Factorial of given number:%lu",f);
getch();
}
unsigned long fact(int x)
{
unsigned long f=1;
while(x>=1)
{
f=f*x;
x--;
}
return f;
}
Program: Write a program to accept any number and display sum of natural numbers using user defined
function
#include<stdio.h>
#include<conio.h>
void main()
{
void sum(int);
int n;
unsigned long f;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
sum(n);
getch();
}
void sum(int x)
{
int i=0,sum=0;
while(i<=x)
{
sum=sum+i;
i++;
}
printf("Sum is %d",sum);
}
Program: Write a program to display the Fibonacci series of n terms using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void fibo();
//fun declaration;
clrscr();
fibo();
getch();
//fun calling;
}
void fibo()
//fun definition
{
int n,t,t1=0,t2=1,i;
clrscr();
printf("Enter no of terms:");
scanf("%d",&n);
printf("Fibonacci series:");
printf("%d\t%d",t1,t2);
for(i=1;i<=n-2;i++)
{
t=t1+t2;
printf("\t%d",t);
t1=t2;
t2=t;
}
}
Storage Classes
The scope and lifetime of variables in functions:Variables in C different behavior from those in most other
language. For example in a basic program a variable returns
its value through out the program. It is not always the case
in C. It always depends on the storage classes the variable
may assume.
A variable in C can have any one of the four storage
classes.
1.Automatic variables
2.Static Variables
3.External Variables or Global Variables
4.Register Variables.
1.Automatic variables:- These variables are declared
inside the function block.
Storage
Main Memory
Default value
Garbage value
Scope
Local to the block in which it is defined.
Life
The control remains within the block in
which it is
Defined.
Keyword
auto
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
Main Memory
Zero
Scope
Life
Main Memory
Default value
Zero
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Scope
Life
Keyword
global
Program:1
#include<stdio.h>
#include<conio.h>
int a,b;
void main()
{
clrscr();
printf("\n a=%d",a);
printf("\n b=%d",b);
getch();
}
Program:2
#include<stdio.h>
#include<conio.h>
int a=100;
void main()
{
extern int a;
clrscr();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
printf("\n a=%d",a);
getch();
}
4.Register Variables:- We can use register variables for
frequently used variables the fast execution of a
program. These variables are declared inside the
function block.
Storage
CPU, Register
Default value
garbage value
Scope
local to the block in which it is defined
Life
the control remains within the block in
which it is defined
Keyword
Register
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
register int a,b;
clrscr();
printf("\n a=%d",a);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
printf("\n b=%d",b);
getch();
}
Note:- If there is no storage classes specifier before the
function declaration of variables inside the function block by
default it takes auto storage class.
Recursive function:- Calling a function with the same name
function definition is known as recursive function. If you
want to work with recursive function we must follow two
conditions.
1.Calling itself
2.Termination condition
Program: Write a program to display natural numbers from
1 to given number using recursive function
#include<stdio.h>
#include<conio.h>
void main()
{
void disp(int);
int n;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
disp(n);
getch();
}
void disp(int x)
{
if(x>1)
disp(x-1);
printf("%d\t",x);
}
Program: Write a program to display natural numbers from
one to given number using recursive function calling
main with in main.
#include<stdio.h>
#include<conio.h>
void main()
{
Static int i=1;n;
If(i==1)
{
Clrscr();
Printf(Enter any number:);
Scanf(%d,&n);
Printf(Natural numbers from 1 to %d:,n);
}
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Printf(%d\t,i);
i++;
if(i<=n)
main();
getch();
exit(0);
}
Program: Write a program to calculate and display factorial of given number
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int n;
unsigned long f;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
f=fact(n);
printf("Factorial is:%lu",f);
getch();
}
unsigned long fact(int x)
{
if(x<=1)
return 1;
else
return x*fact(x-1);
}
Program: Write a program to display reverse number of given number
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long revnum(int);
int n;
unsigned long r;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
r=revnum(n);
printf("reverse number is:%lu",r);
getch();
}
unsigned long revnum(int x)
{
static unsigned long rev=0;
rev=rev*10+(x%10);
x=x/10;
if(x>0)
revnum(x);
return rev;
}
MATH.H FUNCTIONS
abs():- abs (a macro) gets the absolute value of an integer
Syntax:- int abs(int x);
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,a;
clrscr();
printf("Enter any two numbers:");
scanf("%d",&n);
a=abs(n);
printf("Absolute value:%d",a);
getch();
}
sqrt():-It calculates the square root of the given number.
Syntax:- double sqrt(double x);
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n;
double s;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
s=sqrt(n);
printf("Square root of given number:%.2lf",s);
getch();
}
pow():- It calculates the exponential value of given base and power.
Syntax:- double pow(double x, double y);
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int b,p;
double e;
clrscr();
printf("Enter any two value into b and p is:");
scanf("%d%d",&b,&p);
e=pow(b,p);
printf("Exponential value of %d and %d is %.2lf",b,p,e);
getch();
}
floor():- It rounds down the given value.
Syntax:- double floor(double x);
ceil():- It rounds up the given value.
Syntax:- double ceil(double x);
Program:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
double n,ce,fl;
clrscr();
printf("Enter any value:");
scanf("%lf",&n);
ce=ceil(n);
fl=floor(n);
printf("\nCeil value:%.2lf",ce);
printf("\nFloor value:%.2lf",fl);
getch();
}
Program:#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,d,max,min;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
c=a+b;
d=abs(a-b);
max=(c+d)/2;
min=(c-d)/2;
printf("\nMaximum value:%d",max);
printf("\nMinimum value:%d",min);
getch();
}
Program: Write a program to calculate and display area of triangle with the given three sides
Note:-Any two angles greater than equal to third angle
Not form:- 3,4,7 because
3+4=7
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<process.h>
void main()
{
float a,b,c,s,area;
clrscr();
printf("Enter three sides of triangle:");
scanf("%f%f%f",&a,&b,&c);
if((a+b)<=c || (b+c)<=a || (c+a)<=b)
{
printf("Unable to form triangle");
getch();
exit(0);
}
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area = %.3fsqunits",area);
getch();
}
Program: Write a program to enter principle amount, time, and rate of interest calculate and
display total amount, with compound interest
t=p*(1+r/10)power of n
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int m,y,n;
float pr,ta,r;
clrscr();
printf("Enter principle amount:");
scanf("%f",&pr);
printf("Enter rate of interest:");
scanf("%f",&r);
printf("Enter time (Year & Month):");
scanf("%d%d",&y,&m);
n=y*12+m;
ta=pr*pow(1+r/100,n);
printf("Total amount with compound interest:%.2f",ta);
getch();
}
Program: Write a program to compute the following series
1+1/2+1/3+----------+1/n
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i;
float sum=0;
clrscr();
printf("Enter the value of n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+(float)1/i; //type casting
}
printf("Sum = %.2f",sum);
getch();
}
Program: Write a program to compute the following exponential series
cpower of x=1+1/x+xsquare/2!+xqube/3!+---+xpowerof n/n!
#include<stdio.h>
#include<conio.h>
#include<math.h>
unsigned long fact(int x)
{
if(x<=1
return 1;
else
return x*fact(x-1);
}
void main()
{
int n,x,i;
float sum=0;
clrscr();
printf("Enter x and n values:");
scanf("%d%d",&x,&n);
for(i=0;i<=n;i++)
{
sum=sum+pow(x,i)/fact(i);
}
printf("Sum = %.2f",sum);
getch();
}
Program:
Sinx Series
x-xcube/3!+xpower5/5!-xpower7/7!+--------#include<stdio.h>
#include<conio.h>
#include<math.h>
unsigned long fact(int x)
{
if(x>=1)
return 1;
else
return x*fact(x-1);
}
void main()
{
int i,x,n,p=1;
float sum=0;
clrscr();
printf("Enter x and n values:");
scanf("%d%d",&x,&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
sum=sum-pow(x,p)/fact(p);
else
sum=sum+pow(x,p)/fact(p);
p=p+2;
}
printf("Sum = %.2f",sum);
getch();
}
Program:
cosx series cosx=1-xsquare/2!+xpower4/4!-xpower6/6!+--------#include<stdio.h>
#include<conio.h>
#include<math.h>
unsigned long fact(int x)
{
if(x>=1)
return 1;
else
return x*fact(x-1);
}
void main()
{
int i,n,x,p=0;
float sum=0;
clrscr();
printf("Enter n & p values:");
scanf("%d%d",&n,&p);
for(i=1;i<=n;i++)
{
if(i%2==0)
sum=sum=pow(x,p)/fact(p);
else
sum=sum+pow(x,p)fact(p);
p=p+2;
}
printf("Sum = %.2f",sum);
getch();
}
ARRAYS
Definition:-A group of data items (variables) of same data types stored in a continuous memory location is
known as arrays.
That means a group of related data items that shape location name that particular is indicated or
subscript in square braces [ ] or array name. C Supports 3 types of arrays. They are
1. Single Dimension arrays or One dimensional
2. Double Dimension arrays or Two dimensional
3. Multidimensional arrays
1. Single Dimensional array: A group of items can be given one variable name using only index such as a
variable is known as single dimensional array. Single dimensional arrays the elements are represented one or
two index of memory bytes.
Declaration: datatype arr_name[size];
Example:
Elements:
int a[5];
a[0], a[1], a[2], a[3], a[4]
Initialization: [Form1]
Datatype arr_name[size]={value 1, value 2,. Value b} Here size is optional
Example:
int a[5]={1,2,3,4,5};
Int a[ ]={100,200,300,400};
Program: Write a program to initialize single dimensional array elements
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[5]={1,2,3,4,5};
int i;
clrscr();
for(i=0;i<5;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
getch();
}
Program: Write a program to single dimensional array and read values from keyboard
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[20],n,i;
clrscr();
printf("Enter number of elements:");
scanf("%d",&n);
if(n>20)
{
printf("Array index out of bonds");
getch();
exit(0);
}
for(i=0;i<n;i++)
{
printf("\n Given value in a[%d]=%d",i,a[i]);
}
getch();
}
Program: Write a program to accept single dimensional integer array to find the biggest, smallest elements in
the given array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,big,small,i;
clrscr();
printf("Enter array elements:");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
big=a[0];
small=a[0];
for(i=1;i<n;i++)
{
if(a[i]>big)
big=a[i];
if(a[i]<small)
small=a[i];
}
printf("Biggest value:%d",big);
printf("\nSmallest value:%d",small);
getch();
}
Program:- Write a program to accept the single dimensional integer array and display element in reverse
order.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,rev,i;
clrscr();
printf("Enter no.of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Given array elements in reverse order:");
for(i=n-1;i>=0;i--)
{
printf("%d\t",a[i]);
}
getch();
}
Program:- Write a program to accept a single dimensional integer array and search specify elements in the
given array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,se,ck=0;
clrscr();
printf("Enter no.of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter element into a[%d]:",i);
scanf("%d",&a[i]);
}
printf("\n\nEnter element to search:");
scanf("%d",&se);
for(i=0;i<n;i++)
{
if(a[i]==se)
{
ck=1;
printf("\n%d Found at a[%d]",se,i);
}
}
if(ck==0)
printf("Element not found");
getch();
}
Program:- Write a program to accept a single dimensional integer array and display array elements in
ascending order
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,j,t;
clrscr();
printf("Enter no.of elements:");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n\nGiven element before sorting:");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
/*sorting*/
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
f(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\n Given elemets after sorting:");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}
Program: Write a program to accept a single dimensional integer array and delete `specified element in the
given array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,j,de,ck=0;
clrscr();
printf("Enter no.of elements:");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Given elements before deletion:");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
printf("\n Enter element to delete:");
scanf("%d",&de);
/*deletion*/
for(i=0;i<n;i++)
{
if(a[i]==de)
{
ck=1;
for(j=i;j<n;j++)
{
a[j]=a[j+1];
}
n--;
}
}
if(ck==0)
printf("Element not found:");
else
{
printf("\n Given elements after deletion:");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
}
getch();
}
Program: Write a program to accept a single dimensional array and insert an element in the given array at a
specified position
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,ie,pos,t;
clrscr();
printf("Enter no.of elemens:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Given elements before insertion:");
for(i=0;i<n;i++)
{
printf("\t %d",a[i]);
}
printf("\n Enter position:");
scanf("%d",&pos);
if(pos>n)
{
printf("\n Invalid position");
getch();
exit(0);
}
printf("\n Enter element to insert:");
scanf("%d",&ie);
/*insertion*/
if(pos==n)
{
a[n]=ie;
n++;
}
else
{
for(i=pos;i<=n;i++)
{
t=a[i];
a[i]=ie;
ie=t;
}
n++;
}
printf("\n Given elements after insertion:");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
getch();
}
Program: Write a program. to accept a single dimensional array(cannot accept duplicate elements) and
display given array elements using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [],int);
void disp(int [],int);
int a[20],n;
clrscr();
printf("Enter no.of elements:");
scanf("%d",&n);
printf("\n Enter array elements:");
accept(a,n);
printf("\n Given array elements:");
disp(a,n);
getch();
}
void accept(int a[],int s)
{
int i,j;
for(i=0;i<s;i++)
{
lb:
scanf("%d",&a[i]);
for(j=0;j<i;j++)
{
if(a[i]==a[j])
{
printf("elements already exists\n");
printf("enter new elements \n");
goto lb;
}
}
}
}
void disp(int a[],int s)
{
int i;
for(i=0;i<s;i++)
{
printf("\t%d",a[i]);
}
}
Program: Write a program to calculate and display insertion and union of given two arrays using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [],int);
void disp(int [],int);
void sort(int [],int);
int in_arr(int [],int [],int [],int,int);
int un_arr(int [],int [],int [],int,int);
int a[20],b[20],c[20],d[20],m,n,x,y;
clrscr();
printf("Enter no.of elements for A:");
scanf("%d",&m);
printf("Enter no.of elements for B:");
scanf("%d",&n);
printf("Enter elements into A\n");
accept(a,m);
printf("Enter elements into B\n");
disp(b,n);
sort(a,m);
sort(b,n);
clrscr();
printf("Elements of A:");
disp(a,m);
printf("\n Elements of B:");
disp(b,n);
x=in_arr(a,b,c,m,n);
printf("\n Insertion of A and B:");
if(x==0)
printf("No.of elements:");
else
disp(c,x);
y=un_arr(a,b,d,m,n);
printf("\n Union of A and B:");
disp(d,y);
getch();
}
void accept(int a[],int m)
{
int i,j;
for(i=0;i<m;i++)
{
lb:
scanf("%d",&a[i]);
for(j=0;j<i;j++)
{
if(a[i]==a[i])
{
printf("Element already exists\n");
printf("Enter new element\n");
}
}
}
}
void disp(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\t %d",a[i]);
}
}
void sort(int a[],int n)
{
int i,j,t;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
int in_arr(int a[],int b[],int c[],int m,int n)
{
int i,j,id=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i]==b[i]);
{
c[id]=a[i];
id++;
}
}
}
return id;
}
int un_arr(int a[],int b[],int d[],int m,int n)
{
int i=0,j=0,k=0;
while(i<m && j<n)
{
if(a[i]<b[j])
{
d[k]=a[i];
i++;
}
else if(a[i]>b[j])
{
d[k]=b[j];
j++;
}
else
{
d[k]=a[i];
i++;
j++;
}
k++;
}
while(i<m)
{
d[k]=a[i];
i++;
k++;
}
while(j<n)
{
d[k]=b[j];
j++;
k++;
}
return k;
}
2. Two dimensional arrays :- A two dimensional array can store a table of values which contains rows and
columns . In two dimensional arrays we use two index values. One for
rows and another for columns.
Declaration:- data type arr_name[row_size][col_size];
Example:int a[2][3];
here elements:- a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
Initialization :Form:1 datatype arr_name[rowsize][colsize]={val-1,val-2,.........,val-n};
Example:- int a[2][3]={1,2,3,4,5,6};
Form:2: datatype arr_name[rowsize][colsize]={ {val-1,val-2,......},
{val-1,val-2,...val-n},{val-1,val-2,....val-n}...........};
Example:- int a[2][3]={ {1,3,4},{2,3,4} };
Program: Write a program to initialize a two dimensional integer array and display array elements.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3]={1,2,3,4,5,6,7,8,9};
//int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i,j;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("\n a[%d][%d]=%d",i,j,a[i][j]);
}
}
getch();
}
Program: Write a program to accept a two dimensional array and display array elements.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[20][20],r,c,i,j;
clrscr();
printf("Enter rows & colos:");
scanf("%d%d",&r,&c);
if(r>20 || c>20)
{
printf("\nInvalid size");
getch();
exit(0);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\nEnter the value into a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\nGiven value in a[%d][%d]:%d",i,j,a[i][j]);
}
}
getch();
}
II method
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[20][20],r,c,i,j;
clrscr();
printf("Enter rows & colos:");
scanf("%d%d",&r,&c);
if(c>20 || r>20)
{
printf("\nInvalid size");
getch();
exit(0);
}
printf("Enter array elements:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n given elements\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
getch();
}
Program: Write a program to accept a two dimensional integer array and display array
elements using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][20],int,int);
void disp(int a[][20],int,int);
int a[20][20],r,c;
clrscr();
printf("Enter rows & colos:");
scanf("%d%d",&r,&c);
transpose(a,at,r,c);
printf("\nTranspose matrix of given matrix:\n");
disp(at,r,c);
getch();
}
void accept(int x[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&x[i][j]);
}
}
}
void disp(int x[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%3d",x[i][j]);
}
printf("\n");
}
}
void transpose(int a[][20],int at[20][20],int r,int c)
{
int i,j;
/*
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
at[j][i]=a[i][j];
}
}*/
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
at[i][j]=a[j][i];
}
}
}
Program: Write a program to accept any two matrix and display the addition of them using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][20],int,int);
void disp(int a[][20],int,int);
void add_matrix(int [][20],int[][20],int [][20],int,int);
int a[20][20],b[20][20],add[20][20],r,c;
clrscr();
printf("Enter rows & colos:");
scanf("%d%d",&r,&c);
printf("\nEnter first matrix:");
accept(a,r,c);
printf("\n Enter second matrix:");
accept(b,r,c);
clrscr();
printf("\n Given first matrix\n");
disp(a,r,c);
printf("\nSecond matrix:\n");
disp(b,r,c);
add_matrix(a,b,add,r,c);
printf("\nAddition of given two matrix:\n");
disp(add,r,c);
getch();
}
void accept(int x[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&x[i][j]);
}
}
}
void disp(int x[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%3d",x[i][j]);
}
printf("\n");
}
}
void add_matrix(int a[][20],int b[20][20],int add[][20],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
add[i][j]=a[i][j]+b[i][j];
}
}
}
Program: Write a program multiplication of given two matrix using functions
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][20],int,int);
void disp(int [][20],int,int);
void mul_mat(int [][20],int [][20],int [][20],int,int,int);
int a[20][20],b[20][20],mul[20][20],m,n,p,q;
clrscr();
printf("\nEnter the first matrix:\n");
scanf("%d%d",&m,&n);
printf("\nEnter the second matrix rows & colos:\n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("Invalid matrix");
getch();
exit(0);
}
printf("\nEnter the first matrix:\n");
accept(a,m,n);
printf("\nEnter the second matrix :\n");
accept(b,p,q);
clrscr();
printf("\nGiven first matrix:\n");
disp(a,m,n);
printf("\nGien second matrix :\n");
disp(b,p,q);
mul_mat(a,b,mul,m,n,q);
printf("\nMultiplication matrix of given two matrix:\n");
disp(mul,m,q);
getch();
}
void accept(int x[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&x[i][j]);
}
}
}
void disp(int x[][20],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%3d",x[i][j]);
}
printf("\n");
}
}
void mul_mat(int a[][20],int b[][20],int mul[][20],int m,int n,int p,int q)
{
int i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
mul[i][j]=0;
for(k=0;k<n;k++)
{
mul[i][j]=mul[i][j]+a[i][k]*b[k][j];
// mul[i][j]+= a[i][k]*b[k][j];
}
}
}
}
3. Multi Dimensional arrays:-C supports arrays of 3 or more dimensions. In multi dimensional arrays we use
more than two index values.
Syntax:- data type arr_name[s1][s2][s3]......[sn];
where s1,s2,s3,......sn are the sizes of the array.
Example:- int a[2][2][3];
When a compiler assigns a character string to a character array it automatically supplies a null character
at the end of the string. Therefore the size should be equal to the maximum no of characters in the string + 1.
gets:- It gets a string from stdin.
puts:- It outputs a string to std output and appends a new line character.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20];
clrscr();
puts("Enter any string:");
gets(st);
printf("Given string:");
puts(st);
getch();
}
getch():- It gets a character from stdin and does not echo to the screen.
getche():- getche gets a character from console, and echoes to the screen. Syntax: int getche(void);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
// ch=getch();
ch=getche();
printf("\nGiven Character:%c",ch);
getch();
}
getchar():- It is a macro that gets a character from stdin.
Syntax: int getchar(void);
putchar():- putchar is a macro that outputs a character on stdout. Syntax: int putchar(int c);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
ch=getchar();
printf("Given character:");
putchar(ch);
getch();
}
STRING HANDLING FUNCTIONS:-
<string.h>
}
}
void box(int sc, int sr, int ec, int er)
{
gotoxy(sc,sr);
printf("%c",218);
gotoxy(sc,er);
printf("%c",192);
gotoxy(ec,sr);
printf("%c",191);
gotoxy(ec,er);
printf("%c",217);
hline(sr,sc+1,ec-1);
hline(er,sc+1,ec-1);
vline(sc,sr+1,er-1);
vline(ec,sr+1,er-1);
}
Program:
#include"design.h"
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
textmode(2);
_setcursortype(0);
gotoxy(38,12);
textcolor(2+BLINK);
cprintf("MADHU");
box(20,5,60,20);
getch();
}
BOX
strrev(st);
printf("Reverse of given string:%s",st);
getch();
}
3) strcpy():- It copies the given string(src) to the specified string(dest).
Syntax: char *strcpy(char *dest, const char *src);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20], st1[20];
clrscr();
printf("Enter any string:");
gets(st);
strcpy(st1,st);
printf("Given String:%s",st);
printf("\nCopied String:%s",st1);
getch();
}
4) strcat():- It appends one string to another.
Syntax: char *strcat(char *dest, const char *src);
Program:
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20],st1[20];
clrscr();
printf("Enter any First string:");
gets(st);
printf("Enter Second String:");
gets(st1);
strcat(st,st1);
printf("Concatenated string:%s",st);
getch();
}
5)strlwr():- It converts all upper case characters in given string into lower case.
Syntax: char *strlwr(char *s);
6)strupr():- It converts all lower case characters in given string into upper case.
Syntax: char *strupr(char *s);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char st[30],st1[30];
clrscr();
printf("Enter first string into lowercase:");
gets(st);
printf("Enter second string into uppercase:");
gets(st1);
strupr(st);
strlwr(st1);
printf("\nFirst string:%s",st);
printf("\nSecond string:%s",st1);
getch();
}
7)strncpy():- Copies at most maxlen characters of src to dest.
Syntax: char *strncpy(char *dest, const char *src, size_t maxlen);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20],st1[20];
int n;
clrscr();
printf("Enter any string:");
gets(st);
printf("Enter no of characters to be copied:");
scanf("%d",&n);
strncpy(st1,st,n);
st1[n]='\0';
printf("Given string:%s\n",st);
printf("Copied string:%s",st1);
getch();
}
8)strcmp():- It compares the given two strings with case sensitivity.
syn:- int strcmp(const char *s1, const char *s2);
9)stricmp():-It compares the given two strings without case sensitivity.
syn:- int stricmp(const char *s1, const char *s2);
10)strcmpi():- It is a macro and it compares two strings with out case sensitivity.
syn:- int strcmpi(const char *s1, const char *s2);
else
printf("Given string is not palindrome");
getch();
}
Program: Write a program to accept a string and display number of characters, no of digits, no of alphabets,
no of words, no of special characters and no of spaces.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[80];
int nc=0,na=0,nd=0,ns=0,nsp=0,nw=0,i;
clrscr();
printf("Enter any string:");
gets(st);
for(i=0;i<strlen(st);i++)
{
if((st[i]>=65 && st[i]<=90) ||(st[i]>=97 && st[i]<=122))
{
na++;
nc++;
}
else if(st[i]>=48 && st[i]<=57)
{
nd++;
nc++;
}
else if(st[i]==32)
{
ns++;
nc++;
nw++;
}
else if(st[i]=='\0')
{
nw++;
}
else
{
nsp++;
nc++;
}
}
printf("\nNO of Characters
:%d",nc);
printf("\nNo of Alphabets
printf("\nNo of digits
printf("\nNo of words
printf("\nNo of special characters
printf("\nNo of Spaces
getch();
:%d",na);
:d",nd);
:%d",nw);
:%d",nsp);
:%d",ns);
}
Program: Write a program to accept any string and drop one by one character from top to bottom and bottom
to top
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
void main()
{
char st[20];
int c,i,j;
clrscr();
textmode(2);
_setcursortype(0);
textcolor(GREEN);
printf("Enter any string:");
gets(st);
while(1)
{
clrscr();
c=(80-strlen(st))/2;
gotoxy(c,1);
printf("%s",st);
for(i=0;i<=strlen(st);i++)
{
if(st[i]!=32)
{
for(j=2;j<=25;j++)
{
if(kbhit())
exit(0);
gotoxy(c,j);
printf("%c",st[i]);
gotoxy(c,j-1);
printf("%c",32);
delay(20);
}
}
c++;
}
for(i=strlen(st)-1;i>=0;i--)
{
c--;
if(st[i]!=32)
{
for(j=24;j>=1;j--)
{
if (kbhit())
exit(0);
gotoxy(c,j);
printf("%c",st[i]);
gotoxy(c,j+1);
printf("%c",32);
delay(20);
}
}
}
}
}
USER DEFINED FUNCTIONS
Program:
string length
#include<stdio.h>
#include<conio.h>
int stringlen(char st1[])
{
int i=0;
while(st1[i]!='\0')
{
i++;
}
return i;
}
void main()
{
char st[20];
int len;
clrscr();
printf("Enter any string:");
gets(st);
len=stringlen(st);
printf("length of given string:%d",len);
getch();
}
Program:
strrev
#include<stdio.h>
#include<conio.h>
void stringrev(char st1[])
{
int len=0,j,i;
char ch;
while(st1[len]!='\0')
{
len++;
}
j=len-1;
i=0;
while(i<j)
{
ch=st1[i];
st1[i]=st1[j];
st1[j]=ch;
i++;
j--;
}
}
void main()
{
char st[20];
clrscr();
printf("Enter any string:");
gets(st);
stringrev(st);
printf("Reverse of given string:%s",st);
getch();
}
Program:
string copy
#include<stdio.h>
#include<conio.h>
void stringcopy(char dest[], char src[])
{
int i;
for(i=0;src[i]!='\0';i++)
{
dest[i]=src[i];
}
dest[i]='\0';
}
void main()
{
char st[80],st1[80];
clrscr();
printf("Enter any string:");
gets(st);
stringcopy(st1,st);
printf("Given string:%s",st);
printf("\nCopied string:%s",st1);
getch();
}
Program:
stringcat
#include<stdio.h>
#include<conio.h>
void stringcat(char st1[],char st2[])
{
int i=0,j;
while(st1[i]!='\0')
{
i++;
}
for(j=0; st2[j]!='\0';j++)
{
st1[i]=st2[j];
i++;
}
st1[i]='\0';
}
void main()
{
char st1[80],st2[80];
clrscr();
printf("Enter first string:");
gets(st1);
printf("Enter Second String:");
gets(st2);
stringcat(st1,st2);
printf("Concatenation of two strings:%s",st1);
getch();
}
Program:
strncopy
(copies specified no of characters)
#include<stdio.h>
#include<conio.h>
void stringcpy(char dest [],char src[],int n)
{
int i,len=0;
while(src[len]!='\0')
{
len ++;
}
if(n>len)
n=len;
for(i=0;i<n;i++)
{
dest[i]=src[i];
}
dest[i]='\0';
}
void main()
{
char st[80],st1[80];
int n;
clrscr();
printf("Enter any string:");
gets(st);
printf("Enter no of characters to be copied:");
scanf("%d",&n);
stringcpy(st1,st,n);
printf("Given string:%s",st);
printf("\nCopied string:%s",st1);
getch();
}
Program:
string upper and string lower case and lower to upperscase:#include<stdio.h>
#include<conio.h>
void stringupr(char st[])
{
int i;
for(i=0;st[i]!='\0';i++)
{
if(st[i]>=97 && st[i]<=122)
st[i]=st[i]-32;
}
}
void stringlwr(char st[])
{
int i;
for(i=0;st[i]!='\0';i++)
{
if(st[i]>=65 && st[i]<=90)
st[i]=st[i]+32;
}
}
void main()
{
char st[80];
clrscr();
printf("Enter any string:");
gets(st);
printf("Given string:%s",st);
stringlwr(st);
printf("\nGiven string in lower case:%s",st);
stringupr(st);
printf("\nGiven string in upper case:%s",st);
getch();
}
Program:
string case ignore comparison
#include<stdio.h>
#include<conio.h>
int stringcmp(char st1[],char st2[])
{
int i,k;
for(i=0;st1[i]!='\0';i++)
{
if(st1[i]!=st2[i])
break;
}
k=st1[i]-st2[i];
return k;
}
void main()
{
char st1[80],st2[80];
int k;
clrscr();
printf("Enter first string:");
gets(st1);
printf("Enter second string:");
gets(st2);
k=stringcmp(st1,st2);
if(k==0)
printf("Two strings are equal");
else if(k<0)
printf("First string is lessthan second string");
else
printf("First string is greaterthan second string");
getch();
}
Program:
#include<stdio.h>
(Stringicmp)
#include<conio.h>
int stricmp(char st1[],char st2[])
{
char ch1,ch2;
int i,k;
for(i=0;st1[i]!='\0';i++)
{
ch1=st1[i];
ch2=st2[i];
if(ch1>=65 && ch1<=90)
ch1=ch1+32;
if(ch2>=65 && ch2<=90)
ch2=ch2+32;
if(ch1!=ch2)
break;
}
k=ch1-ch2;
return k;
}
void main()
{
char st1[80],st2[80];
int k;
printf("Enter first string:");
gets(st1);
printf("Enter second string:");
gets(st2);
k=stricmp(st1,st2);
if(k==0)
printf("Two strings are equal");
else if(k<0)
printf("First string is less than second string");
else//else(k>0)
printf("First string is greaterthan second string");
getch();
}
Program: Write a program to accept any string and count no of characters,no of words,no of spaces in
the given string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[80];
int nc=0,nw=0,ns=0,i;
clrscr();
printf("Enter any string:");
gets(st);
for(i=0;i<=strlen(st);i++)
{
nc++;
if(st[i]==32 || st[i]=='\0')
{
nw++;
nc--;
if(st[i]==32)
ns++;
}
}
printf("\nNo of characters:%d",nc);
printf("\nNo of spaces:%d",ns);
printf("\nNo of words:%d",nw);
getch();
}
Textmode():-It Changes screen mode (in text mode)
Declaration: void textmode(int newmode);
Constant
ValueText
Mode
LASTMODE
-1
Previous text mode
BW40
0
Black and white
C40
1
Color
BW80
2
Black and white
C80
3
Color
MONO
7
Monochrome
C4350
64
EGA and
VGA
50-line
Textcolor():- It selects new character color in text mode.
Syntax: void textcolor(int newcolor);
40 columns
40 columns
80 columns
80 columns
80 columns
43-line
{
char st[20],ch;
int i,c;
clrscr();
textmode(2);
_setcursortype(0);
printf("Enter any string:");
gets(st);
strupr(st);
clrscr();
strcat(st,"--------");
c=(80-strlen(st))/2;
gotoxy(c,12);
textcolor(RED);
textbackground(WHITE);
cprintf("%s",st);
while(!kbhit())
{
ch=st[0];
for(i=0;i<strlen(st);i++)
{
st[i]=st[i+1];
}
st[i-1]=ch;
st[i]='\0';
gotoxy(c,12);
cprintf("%s",st);
delay(60);
}
getch();
}
Two Dimensional Character arrays:-A list of names can be treated as a table of strings and two dimensional
character array can be used to store the entire list.
For example:-char st[20][20] may be used to store a list of 20 names, each of length
not more than 20 characters.
Initialization: char identifier[rowsize][column size]={string1,string2,-------stringn};
Example: char st[5][10]={madhu,priya,---------aparna};
Program: `
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20][20];
int n,i;
clrscr();
printf("Enter no of strings:");
scanf("%d",&n);
printf("Enter %d strings:\n",n);
fflush(stdin);
for(i=0;i<n;i++)
{
gets (st[i]);
}
printf("Given strings:\n");
for(i=0;i<n;i++)
{
puts(st[i]);
}
getch();
}
Program: Write a program to accept any two dimensional character array and sort them and display in
alphabetical order.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[20][20],t[20];
int n,i,j,k;
clrscr();
printf("Enter no of strings:");
scanf("%d",&n);
printf("Enter %d strings :\n",n);
fflush(stdin);
for(i=0;i<n;i++)
{
gets(st[i]);
}
printf("Given string before sorting:\n");
for(i=0;i<n;i++)
{
puts(st[i]);
}
//sorting
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
k=stricmp(st[i],st[j]);
if(k>0)
{
strcpy(t,st[i]);
strcpy(st[i],st[j]);
strcpy(st[j],t);
}
}
}
printf("Given string after sorting:\n");
for(i=0;i<n;i++)
{
puts(st[i]);
}
getch();
}
POINTERS
C provides the important feature of data manipulations with the address of the variables, the execution
time is very much reduced such concept is possible with the special data type called Pointers.
Pointer:- A pointer is a variable which stores the address of another variable.
Declaration:-Pointer declaration is similar to normal variable declaration but preceded by a *
Syntax:- data type *identifier;
Example:- int *p;
Initialization:- datatype *identifier=address;
Example:- int n;
int *p=&n;
NULL:-NULL pointer value(empty address)
Any type of pointer allocates two bytes of memory because it stores address of memory
allocation.In c language the programme keep ([memory]) size is 64 kilo bytes.It is in unsigned integer range.
NOTE:- Any type of pointer it allocates 2 bytes memory. Because it stores address of memory location.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int *p1;
char *p2;
float *p3;
double *p4;
clrscr();
printf("\n Size of int pointer:%d bytes", sizeof(p1)); //size of(*)
Call by Reference:- The process of calling a function using pointers to pass the address of the variables is
known as call by reference.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void disp(int *);
int n;
clrscr();
disp(&n);
printf("%5d",n);
getch();
}
void disp( int *x)
{
printf("Enter any value into n:");
scanf("%d",x);
}
Program:
Swapping two values
#include<stdio.h>
#include<conio.h>
void main()
{
void swap(int *, int *);
int a,b;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b);
printf("\nBefore swaping:");
printf("\na=%d",a);
printf("\nb=%d",b);
swap(&a,&b);
printf("\nAfter swaping:");
printf("\na=%d",a);
printf("\nb=%d",b);
getch();
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int eno;
char ename[20];
float sal;
void accept(int *, char[],flaot *);
clrscr();
accept(&eno,ename,&sal);
printf(\n emp no:);
printf(\nemp name:);
printf(\nemp sal:);
getch();
}
void accept(int *no, char name[],float *s);
{
printf(enter eno:);
scanf(%d,no);
printf(enter ename:);
gets(name);
printf(enter salary:);
scanf(%f,s);
}
Employee details
The base address is the location of the first element (index 0 of the array).The compiler also defines the
array name as a constant pointer pointed to the first element.
suppose we declare an array 'a' as follows.
Example:- int a[5]={1,2,3,4,5};
Suppose the base address of a is 1000 and assuming that each integer requires 2 bytes. Then the 5
elements will be stored as follows.
Elements------> a[0] a[1] a[2] a[3] a[4]
-----------------------------values------->
1 2 3 4
5
----------------------------address------> 1000 1002 1004 1006 1008
base address
Here 'a' is a pointer that points to the first element. so the value of a is 1000 there fore a=&a[0]=1000
If we declare 'p' is an integer pointer, then we can make the pointer p to point to the array 'a' by the
following assignment.
int *p;
p=&a[0]=a;
Now we can access every value of a using p++(or)p+1 to move one element to another.
The relationship between p and a is shown below.
p+0 = &a[0]=1000
p+1 = &a[1]=1002
p+2 = &a[2]=1004
p+3 = &a[3]=1006
p+4 = &a[4]=1008
When handling arrays instead of using array indexing, we can use pointer to access array elements. Note
that *(p+k) gives the value of a[k]. Pointer accessing method is much faster than array indexing.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n[5];
int *p=n;
clrscr();
printf("n[0]=%u",&n[0]);
printf("\nn=%u",n);
printf("\nn[0]=%u",p);
getch();
}
Program: Write a program to accept and display array elements using pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i;
int *p=&a[0];
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%5d",p+i);
}
printf("Given array elements:");
for(i=0;i<n;i++)
{
printf("%5d",*(p+i));
}
getch();
}
DYNAMIC MEMORY ALLOCATION
C language requires the no of elements in an array to be specified at compile time.But we may not be
able to do so always our initial judgement of size,if it is wrong,it make cause failure of the program (or) wastage
of the memory space.In this situation we use Dynamic Memory allocation.
Definition:-The process of allocating memory at run time is known as Dynamic memory allocation.
Malloc():<alloc.h>
It is a function which is used to allocating memory at run time.
Syntax:- void *malloc(size_t size);
size_t:- unsigned integer. this is used for memory object sizes.
Pointer variable=(type casting)malloc(memory size);
Example:- int *p;
p=(int *)malloc(sizeof(int)); //for 1 location
p=(int *)malloc(n*sizeof(int)); //for n locations
Calloc():<alloc.h>
This is also used for allocating memory at run time.
Syntax: void *calloc(size_t nitems, size_t size);
NOTE:- Calloc allocates a block (n times*size)bytes and clears into 0.
Difference between malloc and calloc:
1. Malloc defaultly store garbage value where as calloc defaultly stores zero
2. In malloc only one argurment we will pass where as in calloc we will pass two arguments
Program:Write a program to create a dynamic array (vector) store values from keyboard
display
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int *a,n,i;
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
a=(int *)malloc(n* sizeof(int));
//a=(int *)calloc(n,sizeof(int));
printf("Enter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
printf("Given array elements:");
for(i=0;i<n;i++)
{
printf("%d\t",*(a+i));
}
getch();
}
Program: Write a program to create a dynamic memory allocation for two dimensional array and read values
from keyboar and display
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int **a,r,c,i,j;
clrscr();
printf("Enter no of rows and columns:");
scanf("%d%d",&r,&c);
a=(int **)malloc(r* sizeof(int *));
//a=(int *)calloc(n,sizeof(int));
for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(c*sizeof(int));
}
printf("enter array elements:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",*(a+i)+j);
}
}
printf("Given array elements:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d\t",*(*(a+i)+j));
}
printf("\n");
}
free(a);
getch();
}
Program:Write a program to create a variable to columnsize array in read values
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int **a,r,*c,i,j;
clrscr();
printf("Enter no of rows:");
scanf("%d",&r);
c=(int *)malloc(r* sizeof(int));
//a=(int *)calloc(n,sizeof(int));
for(i=0;i<r;i++)
{
printf("enter no of cols for row %d:",i+1);
scanf("%d",c+i);
}
a=(int **)malloc(r* sizeof(int *));
for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(*(c+i)*sizeof(int));
}
printf("enter array elements:\n");
for(i=0;i<r;i++)
{
for(j=0;j<*(c+i);j++)
{
scanf("%d",*(a+i)+j);
}
}
printf("Given array elements:\n\n");
for(i=0;i<r;i++)
{
for(j=0;j<*(c+i);j++)
{
printf("%3d\t",*(*(a+i)+j));
}
printf("\n");
}
free(a);
getch();
}
Realloc():- It reallocates Main memory.
Syntax:-
Syntax:-
{
int n;
clrscr();
p(enter any number:);
s(%d,&n);
#undef p
printf(given value:%d,n);
getch();
}
Macro with arguments:-The preprocessor permits us to define more complex and more useful form of
replacements.
Syntax:
#define identifier(arg-1,arg-2,.....arg-n) definition
Example:
#define square(x) x*x
Program:
#include<stdio.h>
#include<conio.h>
#define square(x) x*x
void main()
{
int n,s;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
s=square(n);
printf
}
Program:
max of given two values
#include<stdio.h>
#include<conio.h>
#define maxval(x,y)x>y?s:y
void main()
{
int a,b,m;
clrscr();
printf(enter any two values:);
scanf(%d%d,&a,&b);
m=maxval(a,b);
printf(maximum value:%d,m);
getch();
}
Difference between Function and Macro
Function
1. It is a self contained block of statements.
2. It replaces its return value
Macro
1. It is a preprocessor statement
2. It replaces its definition
struct struct_name
{
data item-1;
data item-2;
----------------------data item-n;
};
Example:
struct emp
{
int eno;
char ename[80];
float sal;
};
Declaration of structure variable:- struct struct_name identifier;
Example:-struct emp e;
Access operator:- (.)It is used to access the data items of the structure with the help of
structure variable.
Example:-e.eno;
e.ename;
e.sal;
Initialization:-struct struct_name identifier={val-1,val-2,.....val-n};
Example:- struct emp e={100,"gouse",10000};
Form 2: Declaration of struct and structure variable in a single statement
struct struct_name
{
data item-1;
data item-2;
---------------------data item-n;
}var_list;
Example:
struct emp
{
int eno;
char ename[80];
float sal;
}e;
Initialization:
Example:
struct emp
{
int eno;
char ename[80];
float sal;
}e={100,"gouse",10000};
Programs:
#include<stdio.h>
#include<conio.h>
struct test
{
int n;
};
void main()
{
struct test t;
clrscr();
printf("Size of structure:%d",sizeof(struct test));
printf("\nEnter any number in n:");
scanf("%d",&t.n);
printf("Given number in n:%d",t.n);
getch();
}
Programs:
Initializsation
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[20];
float sal;
}e={100,"PRIYA",12000};
void main()
{
// struct emp e={100,"PRIYA",12000};
clrscr();
printf("Size of structre :%d",sizeof(struct emp));
printf("\nGiven employee number:%d",e.eno);
printf("\nGiven employee name :%s",e.ename);
printf("\nGiven employee salary:%f",e.sal);
getch();
}
Program:
Declaration: //26bytes(2 for int,1 for each character and 4 for float)
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[20];
float sal;
}e;
void main()
{
// struct emp e;
clrscr();
printf("Size of structre :%d",sizeof(struct emp));
printf("\nEnter employee number:");
scanf("%d",&e.eno);
printf("Enter employee name:");
fflush(stdin);
gets(e.ename);
printf("Enter employee salary:");
scanf("%f",&e.sal);
printf("\nGiven employee number:%d",e.eno);
printf("\nGiven employee name :%s",e.ename);
printf("\nGiven employee salary:%f",e.sal);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
struct student
{
int sno,c,cpp,unix,tot;
char sname[20],res[10],div[10];
float avg;
}s;
void main()
{
// struct student s;
clrscr();
printf("Size of structre:%d",sizeof(struct student));
{
strcpy(s.res,"PASS");
if(s.avg>=60)
strcpy(s.div,"FIRST");
else
strcpy(s.div,"SECOND");
}
else
{
strcpy(s.res,"FAIL");
strcpy(s.div,"NO_DIVISION");
}
clrscr();
printf("\n Student number:%d",s.sno);
printf("\n Student name :%s",s.sname);
printf("\n Marks in C:%d",s.c);
printf("\n Marks in Cpp:%d",s.cpp);
printf("\n Marks in unix:%d",s.unix);
printf("\n Total Marks:%d",s.tot);
printf("\n Average Marks:%.2f",s.avg);
printf("\n Result:%s",s.res);
printf("\n Division:%s",s.div);
getch();
}
ARRAYS AND STRUCTURES
Like any other data type structure arrays can be defined. So that each array element can be of structure
data type.
Example: Struct item it[100];
It defines an array called it, that contains of 100 elements. Each element is defined to be the type struct
item.
Program:
#include<stdio.h>
#include<conio.h>
struct item
{
int ino;
char iname[20];
float cost;
};
void main()
{
struct item it[20];
int n,i;
float *f,f1;
clrscr();
f=&f1;
*f=f1;
printf("Enter no of records:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter record%d:\n",i+1);
printf("Enter item number:");
scanf("%d",&it[i].ino);
printf("Enter item name:");
fflush(stdin);
gets(it[i].iname);
printf("Enter item cost:");
scanf("%f",&it[i].cost);
}
clrscr();
printf("\nGiven records:\n");
printf("%-10s%-15s%s","INO","INAME","ICOST");
printf("\n-------------------------------");
for(i=0;i<n;i++)
{
printf("\n%-10d%-15s%.2f",it[i].ino,it[i].iname,it[i].cost);
}
getch();
}
STRUCTURES AND POINTERS
A pointer can also point to a structure for example
Example:struct student
{
int sno;
char sname[80];
int m1,m2,m3;
};
struct student s;
struct student *p;
Here P is a pointer pointing student structure. Hence we can write p=&s;
After making such an assignment, we can access every data item of student structure indirectly through p as
follows.
(*p).sno;
(*p).sname;
(*p).m1;
(*p).m2;
(*p).m3;
Here instead of writing '.' and '*' we use the structure pointer operator"arrow (->)".Which is - and
followed by > sign.
This means we can access every item of student structure through p as follows.
p->sno;
p->sname;
p->m1;
p->m2;
p->m3;
Program:
Structures with Dynamic memory allocation with (single records)
#include<stdio.h>
#include<conio.h>
struct item
{
int ino;
char iname[20];
float cost;
};
void main()
{
struct item it,*p;
float *f,f1;
clrscr();
f=&f1;
*f=f1;
pt=(struct item *)malloc(n*sizeof(struct item));
printf("Enter item number:");
scanf("%d",&p->ino);
printf("Enter item name:");
fflush(stdin);
gets(p->iname);
printf("Enter item cost:");
scanf("%f",&p->cost);
printf(\n item number
:%d,p->ino);
printf(\n Item name
:%s,p->iname);
printf(\n item cost
:%f,p->cost);
getch();
}
Program:
Structure with Dynamic memory allocation with multiple records
#include<stdio.h>
#include<conio.h>
struct item
{
int ino;
char iname[20];
float cost;
};
void main()
{
struct item *it;
int n,i;
float *f,f1;
clrscr();
f=&f1;
*f=f1;
printf("Enter no of records:");
scanf("%d",&n);
it=(struct item *)malloc(n*sizeof(struct item));
for(i=0;i<n;i++)
{
printf("Enter record%d:\n",i+1);
printf("Enter item number:");
scanf("%d",&(it+i)->ino);
//scanf(%d,&(*it+i).ino);
printf("Enter item name:");
fflush(stdin);
gets((it+i)->iname);
printf("Enter item cost:");
scanf("%f",&(it+i)->cost);
}
clrscr();
printf("\nGiven records:\n");
printf("%-10s%-15s%s","INO","INAME","ICOST");
printf("\n-------------------------------");
for(i=0;i<n;i++)
{
printf("\n%-10d%-15s%.2f",(it+i)->ino,(it+i)->iname,(it+i)->cost);
}
getch();
}
Passing Structure as a function argument as well as return type:-Like any other data type a structure may
be used as function argument.
Returning structure:-A function can not only received structure as its argument but also can return them.
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[20];
float sal;
};
struct emp accept()
{
struct emp e;
printf("Enter emp number:");
scanf("%d",&e.eno);
printf("Enter emp name:");
fflush(stdin);
gets(e.ename);
printf("Enter emp salary:");
scanf("%f",&e.sal);
return e;
}
void disp(struct emp x)
{
printf("\nGiven emp number:%d",x.eno);
printf("\nGiven emp name:%s",x.ename);
printf("\nGiven emp salary:%.2f",x.sal);
}
void main()
{
struct emp e;
clrscr();
e=accept();
disp(e);
getch();
}
STRUCTURES WITH IN STRUCTURES (or) NESTED STRUCTURES
Form 1: Declaring a structure within another structure is called structure with in structure.
Example:- struct student
{
int sno,c,cpp,unix;
char sname[20];
struct result
{
int tot;
float avg;
char res[20],div[20];
}r;
}s;
Accessing Data items:s.sno,s.c,s.cpp,s.unix,s.sname;
s.r.tot,s.r.avg,s.r.res,s.r.div;
Form 2: Declaring a structure variable with in another structure is called as structure within structure.
Example: struct student
{
int sno,c,cpp,unix;
char sname[80];
};
struct result
{
struct student s;
int tot;
char res[20],div[20];
float avg;
}r;
Accessing Data items:
r.s.sno , r.s.c , r.s.cpp , r.s.unix , r.s.sname;
r.tot , r.avg , r.div , r.res;
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
int sno,c,cpp,unix;
char sname[20];
struct result
{
int tot;
char res[20],div[20];
float avg;
}r;
}s;
void main()
{
char ch;
do
{
clrscr();
printf("enter student number");
scanf("%d",&s.sno);
printf("enter student name");
fflush(stdin);
gets(s.sname);
printf("enter marks in c,cpp,unix:");
scanf("%d%d%d",&s.c,&s.cpp,&s.unix);
s.r.tot=s.c+s.cpp+s.unix;
s.r.avg=(float)s.r.tot/3;
UNIONS
UNION:- A Union is similar to a struct, except it allows you define
variables that shares common storage space.
Syntax:- union union_name
{
data item-1;
data item-2;
--------------------data item-n;
}var_list;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
Program:
#include<stdio.h>
#include<conio.h>
struct test1
{
int n;
char ch;
float ft;
}t1;
union test2
{
int n;
char ch;
float ft;
}t2;
void main()
{
clrscr();
printf(\nSize of struct:%d Bytes,sizeof(t1));
printf(\nSize of Union:%d Bytes,sizeof(t2));
getch();
}
Differences Between Struct and Union:
Structure
1. A Group of data items that belongs
the
to different data items.
allocation
2. It allocates memory of all declared
data
Union
1.It is also same as structure but
Only
difference
is
memory
Item in it.
3.It can access only one item
4.All items are shared common
Place.
Programs:
#include<stdio.h>
#include<conio.h>
union emp
{
int eno;
char ename[20];
float sal;
}e;
void main()
{
//
union emp s;
clrscr();
printf("\nEnter employee number:");
scanf("%d",&e.eno);
printf("Enter employee name:");
fflush(stdin);
gets(e.ename);
printf("Enter employee salary:");
scanf("%f",&e.sal);
printf("\n Employee number:%d",e.eno);
printf("\n Employee name :%s",e.ename);
printf("\n Employee salaray:%f",e.sal);
getch();
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
}
BIT-FIELDS:-C permits to use small bit fields to hold data.
We have been using integer field of size 16 bits to store data. That data item requires much less than 16
bits of memory space.
In such situations we waste memory space. At this situation we use small bit fields in structures.
The bit field data type is either int Or Unsigned int.
The largest value that can store integer bit field is 2power(n-1).
The largest value that can store unsigned integer bit field is 2power n -1.
Declaration:-struct struct_name
{
int (or) unsigned identifier-1:bitlength;
int (or) unsigned identifier-2:bitlength;
--------------------------------------------------------------------------------int (or) unsigned identifier-n:bitlength;
declaration of normal data items;
};
Example:struct emp
{
unsigned eno:7;
unsigned age:6;
char ename[80];
float sal;
};
NOTE:-The scanf function cannot read small bit fields. Because the scanf function scans and formats data into
2 bytes of address of the integer field.
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
unsigned int eno:7;
char ename[20];
float sal;
};
void main()
{
struct emp e;
int n;
clrscr();
printf("Enter any emp no:");
scanf("%d",&n);
e.eno=n;
printf("Enter any emp name:");
fflush(stdin);
gets(e.ename);
printf("Enter emp salary:");
scanf("%f",&e.sal);
printf("Given emp no:%d",e.eno);
printf("\nGiven emp name:%s",e.ename);
printf("\nGiven emp salary:%f",e.sal);
getch();
}
Pre-Defined Structures:
Date:-It is a pre-defined structure and used to get and set current system data.
Syntax -Struct date
{
int da_year; //current year
char da_year; //day of the month
char da_mo; //month(1=jan)
};
<dos.h>
Getdate(method):-It gets current system data.
Declaration: void getdate(struct date *d);
Setdate:-It sets current system date]
Declaration: void setdate(struct date *d);
Program:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
struct date d;
clrscr();
getdate(&d);
printf("Current system date:%.2d-%.2d-%d",d.da_day,d.da_mon,d.da_year);
getch();
}
Program:
Time: It is pre-defined structure and used to get and set current system time.
Syntax:Struct time
{
Unsigned char ti_min;
//minutes
Unsigned char ti_hour;
//hours
Unsigned char ti_sec;
//seconds
};
Gettime(method):-
<dos.h>
File attributes
:
:
:
:
:
:
:
Description
Read only attribute
Hidden files
System file
Volume lable
Directory
Archive
dir.h
getcwd
clrscr();
getcwd(st,80);
printf("Current working directory:%s",st);
getch();
}
Chdir: It changes current directory
Declaration: int chdir(const char * path);
Return value: on success, return 0;
Program:
chdir
#include<stdio.h>
#include<conio.h>
#include<dir.h>
void main()
{
char path[80];
int k;
clrscr();
printf("Enter path:");
gets(path);
k=chdir(path);
if(k==0)
printf("Directory is changed");
else
printf("Unable to change directory");
getch();
}
Mkdir :It creates a directory .
Declaration: int mkdir(Const char *path);
Return value: on success;
Program:
mk dir
#include<stdio.h>
#include<conio.h>
#include<dir.h>
void main()
{
char path[80];
int k;
clrscr();
printf("Enter path:");
gets(path);
k=mkdir(path);
if(k==0)
printf("Directory is created");
else
enum
void main()
{
clrscr();
printf("\na=%d",a);
printf("\nb=%d",b);
printf("\nc=%d",c);
printf("\nd=%d",d);
printf("\ne=%d",e);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
enum boolean{true,false};
enum boolean iseven(int x)
{
if(x%2==0)
return true;
else
return false;
}
void main()
{
int n;
enum boolean b;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
b=iseven(n);
if(b==true)
printf("Given number is even");
else
printf("Given number is odd");
getch();
}
Typedef:- It assigns the symbol name to the data type definition(type definition).
syntax:- typedef <type definition> <identifier> ;
Program:
#include<stdio.h>
#include<conio.h>
typedef unsigned long ul;
void main()
{
ul n;
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
clrscr();
printf("Enter any number:");
scanf("%lu",&n);
printf("Given number:%lu",n);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[20];
float sal;
};
typedef struct emp se;
se accept()
{
se e;
printf("Enter no:");
scanf("%d",&e.eno);
printf("Enter ename:");
fflush(stdin);
gets(e.ename);
printf("Enter salary:");
scanf("%f",&e.sal);
return e;
}
void display(se e)
{
printf("\nEno:%d",e.eno);
printf("\nEname:%s",e.ename);
printf("\nEsal:%.2f",e.sal);
}
void main()
{
se e;
clrscr();
e=accept();
display(e);
getch();
}
FILES
ARISE, AWAKE AND STOP TILL THE GOAL IS NOT REACHED
C language permits the usage of limited input and output functions to read and write data. These
functions are used for only smaller volumes of data and it becomes difficult to handle longer data volumes. Also
the entire data is lost when the program is over.
To overcome these difficulties a flexible method is developed by employing the concept of FILES to store, to
read (0r) write data and to written them even when program is over.
Definition:-A FILE is one which enable the user to read , write and store a group of a related data . (or) A
FILE is a collection of related data stored in a particular area on the disk.
C supports a number of functions to have the ability to perform the basic file operations which indicates.
1) Naming a file
2) Opening a file
3) Reading data from a file
4) Writing data into file
5) Closing a file
Text file or Sequential file:- For reading ad writing data in continuous blocks in this files the data is
represented instead of characters. Each and every character requires only one byte.
Binary files:- For reading and writing data in orbitary structured files. In this files the information is
represented instead of data blocks the size of data blocks depends on its data type.
FILE:- It is a predefined structure and is used to declare a file pointer. Using this pointer we can perform all file
operations.
Declaration of file pointer:FILE *identifier;
Example:FILE *fp;
fopen():- It opens a file stream.
Syntax: FILE *fopen(const char *filename, const char *mode);
ARGUMENTS
file name:- File that the functions open.
MODE DESCRIPTION:
Sno
1
2
Mode
r
w
r+
Description
Open for reading only
Create for writing (a file by that name already exists, it will be
overwritten.)
end; open for writing at end of file, or create for writing if the file does
not exist.
Open an existing file for update (reading and writing)
w+
a+
*To specify that a given file is being opened or created in text mode, append "t" to the string (rt, w+t, etc.).
*To specify binary mode, append "b" to the string (wb, a+b, etc.).
fclose():- It closes a file stream.
}
Program:Write a program to open a text file read data into that file display on the screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("a.txt","r");
printf("reading data from file: \n");
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
delay(100);
//dos.h
}
fclose(fp);
getch();
}
Program:Write a program to accept any file name and display all contents in the given file
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
FILE *fp;
char st[20],ch;
clrscr();
printf("Enter any file name:");
gets(st);
fp=fopen(st,"r");
if(fp==NULL)
{
printf("File not found");
getch();
exit(0);
}
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
delay(20);
}
fclose(fp);
getch();
}
Rewind: It repositions file pointer file streams beginning
Syntax: void rewind(FILE *stream);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("text.txt","w+");
printf("Enter data into file(ctrl+z to stop)\n");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
printf("\nReading data from file\n");
rewind(fp);
ch=fgetc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=fgetc(fp);
}
fclose(fp);
getch();
}
Program:Write a program to accept any filename and count no of lines, no of words and no of characters in
the given file
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
FILE *fp;
char st[20],ch,ch1;
int nl=0,nw=0,nc=0;
clrscr();
Returns non-zero if an end-of-file indicator was detected on the last input operation on the named stream.
Returns 0 if end-of-file has not been reached.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
char st[80];
clrscr();
fp=fopen("str.txt","a+");
printf("Enter string data into file('end' to stop)\n");
gets(st);
while(strcmpi(st,"end")!=0)
{
fputs(st,fp);
fputs("\n",fp);
gets(st);
}
rewind(fp);
printf("Reading data from file\n");
fgets(st,80,fp);
while(!feof(fp))//while(feof(f)==0)But this is not efficient
{
printf("%s",st);
fgets(st,80,fp);
}
fclose(fp);
getch();
}
fscanf():It scans and formats input from a file stream.
Syntax: int fscanf (FILE *stream,const char *format [, address, ...]);
fprintf():It sends formatted output to the file stream.
Syntax: int fprintf (FILE *stream, const char *format [, argument, ...]);
NOTE:-In fprintf (or) fscanf, between formats atleast one space is neccessary.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
int eno;
char ename[20];
float sal;
clrscr();
fp=fopen("emp.txt","w");
printf("Enter eno:");
scanf("%d",&eno);
printf("Enter ename:");
fflush(stdin);
gets(ename);
printf("Enter salary");
scanf("%f",&sal);
fprintf(fp,"%d %s %.2f",eno,ename,sal);
fclose(fp);
printf("Record is saved successfully");
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int eno;
char ename[20];
float sal;
clrscr();
fp=fopen("emp.txt","r");
fscanf(fp,"%d %s %f",&eno,ename,&sal);
printf("Reading data from file \n");
printf("\nEno:%d",eno);
printf("\nEname:%s",ename);
printf("\nSal:%.2f",sal);
fclose(fp);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int eno;
char ename[20],ch;
float sal;
clrscr();
fp=fopen("emp1.txt","a+");
do
{
printf("Enter eno:");
scanf("%d",&eno);
printf("Enter ename:");
fflush(stdin);
gets(ename);
printf("Enter salary:");
scanf("%f",&sal);
fprintf(fp,"%d %s %.2f\n",eno,ename,sal);
printf("Record is saved successfully\n");
printf("Enter another record(y/n)");
fflush(stdin);
scanf("%c",&ch);
}while(ch!='n');
clrscr();
rewind(fp);
printf("%-10s%-15s%s","ENO","ENAME","SALARY");
printf("\n__________________________________");
while(!feof(fp))
{
fscanf(fp,"%d %s f\n",&eno,ename,&sal);
printf("\n%-10d%-15s%.2f",eno,ename,sal);
}
fclose(fp);
getch();
}
ftell():- It Returns the current file pointer.
Syntax: long ftell(FILE *stream);
Constant
SEEK_SET
SEEK_CUR
SEEK_END
Value
0
1
2
File location
Seeks from beginning of file
Seeks from current position
Seeks from end of file
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("a.txt","w");
printf("Current file pointer position:%d",ftell(fp));
printf("Enter data into file(ctrl+z to stop)\n");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
printf("Present file pointer position:%d",ftell(fp));
fseek(fp,-10,SEEK_CUR);
printf("\nNew file pointer position:%d",ftell(fp));
fclose(fp);
getch();
}
BINARY FILES
putw():-It outputs an integer on a stream.
Syntax: int putw(int w,FILE *stream);
getw():-It gets an integer from stream.
Syntax: int getw(FILE *stream);
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen("num.dat","a+b");
{
FILE *fp;
struct item it;
clrscr();
fp=fopen("item.dat","wb");
printf("Enter item number:");
scanf("%d",&it.ino);
printf("Enter item name:");
fflush(stdin);
gets(it.iname);
printf("Enter cost:");
scanf("%f",&it.cost);
fwrite(&it,sizeof(it),1,fp);
fclose(fp);
printf("Record saved successfully");
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
struct item
{
int ino;
char iname[20];
float cost;
};
void main()
{
FILE *fp;
struct item it;
clrscr();
fp=fopen("item.dat","rb");
fread(&it,sizeof(it),1,fp);
printf("\nItem number:%d",it.ino);
printf("\nItem name:%s",it.iname);
printf("\nItem cost:%.2f",it.cost);
fclose(fp);
getch();
}
Program:
#include<stdio.h>
#include<conio.h>
struct item
{
int ino;
char iname[20];
float cost;
};
void main()
{
FILE *fp;
char ch;
struct item it;
clrscr();
fp=fopen("item.dat","a+b");
do
{
printf("Enter item number:");
scanf("%d",&it.ino);
printf("Enter item name:");
fflush(stdin);
gets(it.iname);
printf("Enter cost:");
scanf("%f",&it.cost);
fwrite(&it,sizeof(it),1,fp);
printf("Record saved successfully");
printf("Enter another record(y/n)");
fflush(stdin);
scanf("%c",&ch);
}while(ch!='n');
clrscr();
fseek(fp,0,0);//new rewind (fp);
printf("%-10s%-15s%s","INO","INAME","COST");
printf("\n_________________________________");
fread(&it,sizeof(it),1,fp);
while(!feof(fp))
{
printf("\n%-10d%-15s%-2f",it.ino,it.iname,it.cost);
fread(&it,sizeof(it),1,fp);
}
fclose(fp);
getch();
}
{
clrscr();
gotoxy(35,5);
printf("MENU");
gotoxy(30,6);
printf("_______________");
gotoxy(30,7);
pritnf("\n1.ADD RECORD");
gotoxy(30,8);
pritnf("\n2.DISPLAY");
gotoxy(30,9);
pritnf("\n3.SEARCH");
gotoxy(30,10);
pritnf("\n4.DELETE");
gotoxy(30,11);
pritnf("\n5.INSERT");
gotoxy(30,12);
pritnf("\n6.UPDATE");
gotoxy(30,13);
pritnf("\n7.EXIT");
gotoxy(30,14);
printf("_________________");
gotoxy(30,16);
printf("Enter your option:");
scanf("%d",&opt);
clrscr();
switch(opt)
{
case 1:
addrecord();
break;
case 2:
display();
break;
case 3:
search_rec();
break;
case 4:
delete();
break;
case 5:
insert();
break;
case 6:
update();
break;
case 7:
exit(0);
}
getch();
}
}
void accept()
{
printf("Enter eno:");
scanf("%d",&e.eno);
pritnf("Enter ename:");
fflush(stdin);
gets(e.ename);
printf("Enter salary:");
scanf("%f",&e.sal);
}
void addrecord()
{
FILE *fp;
char ch;
fp=fopen("emp.dat","ab");
do
{
accept();
fwrite(&e,sizeof(e),1,fp);
printf("Enter another record(y/n):");
fflush(stdin);
scanf("%c",&ch);
}while(ch!='n');
fclose(fp);
}
void header()
{
printf("%-10s%-15s%-15s%s","ENO","ENAME","SALARY");
printf("\n__________________________________");
}
void display()
{
FILE *fp;
int c=0;
fp=fopen("emp.dat","rb");
header();
while(fread(&e,sizeof(e),1,fp)==1)
{
printf("\n%-10d%-15s%.2f",e.eno,e.ename,e.sal);
c++;
if(c%20==0)
{
getch();
clrscr();
header();
}
}
fclose(fp);
}
int search(int n)
{
FILE *fp;
fp=fopen("emp.dat","rb");
while(fread(&e,sizeof(e),1,fp)==1)
{
if(e.eno==n)
{
fclose(fp);
return 1;
}
}
fclose(fp);
return 0;
}
void search_rec()
{
}
}
}
/*w.a.p to create a data file and perform the following menu operations.
MENU
______________
1.Add record
2.Display
3.Search
4.Delete
5.Insert
6.Update
7.Exit
_______________*/
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20],course[20];
float fee;
};
int checkrec(int n)
{
FILE *fp;
struct student s;
fp=fopen("student.dat","rb");
if(fp==NULL)
return 0;
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
if(s.sno==n)
{
fclose(fp);
return 1;
}
fread(&s,sizeof(s),1,fp);
}
fclose(fp);
return 0;
}
struct student accept()
{
struct student s;
lb:
printf("enter student no:");
scanf("%d",&s.sno);
if(checkrec(s.sno)==1)
{
printf("record already exists\n");
printf("Enter another record\n");
goto lb;
}
printf("Enter student name:");
fflush(stdin);
gets(s.sname);
printf("Enter course");
gets(s.course);
printf("Enter fee:");
scanf("%f",&s.fee);
return s;
}
void addrecord()
{
FILE *fp;
struct student s;
fp=fopen("Student.dat","ab");
s=accept();
fwrite(&s,sizeof(s),1,fp);
fclose(fp);
printf("Record saved successfully");
}
void header()
{
printf("%-10s%-15s%-15s%s","SNO","SNAME","COURSE","FEE");
printf("\n---------------------------------");
}
void display()
{
FILE *fp;
struct student s;
int count=0;
fp=fopen("Student.dat","rb");
header();
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
printf("\n%-10s%-15s%-15s%.2f",s.sno,s.sname,s.course,s.fee);
count++;
if(count%20==0)
{
printf("\n\nPress any key to continue.......");
getch();
clrscr();
header();
}
fread(&s,sizeof(s),1,fp);
}
fclose(fp);
}
void search()
{
FILE *fp;
struct student s;
int n;
printf("Enter student number to search:");
scanf("%d",&n);
if(checkrec(n)==0)
{
printf("Record not found");
return;
}
fp=fopen("Student.dat","rb");
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
if(s.sno==n)
{
printf("\n sname:%s",s.sname);
printf("\n course:%s",s.course);
printf("\n fee:%.2f",s.fee);
fclose(fp);
return;
}
fread(&s,sizeof(s),1,fp);
}
}
void delete()
{
FILE *fp1,*fp2;
struct student s;
int n;
printf("Enter student no to delete");
scanf("%d",&n);
if(checkrec(n)==0)
{
printf("Record not found");
return;
}
fp1=fopen("Student.dat","rb");
fp2=fopen("Temp.dat","wb");
fread(&s,sizeof(s),1,fp1);
while(!feof(fp))
{
if(s.sno!=n)
fwrite(&s,sizeof(s),1,fp2);
fread(&s,sizeof(s),1,fp1);
}
remove("student.dat");
rename("temp.dat","student.dat");
printf("Record is deleted");
}
void insert()
{
FILE *fp1,*fp2;
struct student sl;
int n;
char ch;
lb:
printf("Insert before/after(b/B(or)A/a:");
fflush(stdin);
scanf("%c",&ch);
if(ch=='b'||ch=='B')
printf("Before which sno do u want to insert");
elseif(ch=='a'||ch=='A')
printf("After which sno do u want to insert");
else
{
printf("\nInvalid Option");
goto lb;
}
scanf("%d",&n);
if(checkrec(n)==0)
{
printf("Record not found");
return;
}