Ramesh C Notes
Ramesh C Notes
Computer:
Input:
Output:
Software:
System Software:
Operating system:
Application Software:
Package:
Hardware:
All the physical components or units which are
connecting to the computer circuit is known as Hardware.
Small Letters ( a to z) 26
Digits ( 0 to 9) 10
Special Characters 32
Control Characters 34
Eg:
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
Esc 27
Backspace 8
Enter 13
SpaceBar 32
Tab 9
etc.
Translators:
These are used to convert low or high level
language instructions into machine language
with the help of ASCII character set. There are
3 types of translators for languages.
1) Assembler :
It is used to convert low level language
instructions into machine language.
2) Compiler:
It is used to convert high level language
instructions into machine language. It
checks for the errors in the entire program
and converts the program into machine
language.
3)Interpreter:
It is also used to convert high level
language instructions into machine language,
But It checks for errors by statement wise
and converts into machine language.
Debugging :
The process of correcting errors in the
program is called as debugging.
3.Algorithm:
A step by step procedure to solve the given
problem is called as algorithm. An algorithm
can be described in a natural language such as
English.
4.Flow chart:
A symbolic or graphical representation of given
algorithm is called as flow chart.
7.Documentation:
Algorithms:
Steps:
1. start
2. Read A and B
3. max=A
4. if (max<B) then max=B
5. print max
6. stop
1. start
2. Read A, B and C
3. max=A
4. if(max < B) then max=B
5. if(max < C) then max=C
6. print max
7. stop
Steps:
1. start
2. Read n
3. if(n%2=0) then print "Given number is
even" else
print "Given number is odd"
4. stop
Steps:
1. start
2. Read n
3. rev=0
4. rev=(rev*10)+(n%10)
5. n=n/10
6. if(n>0) then goto step 4
7. print rev
8. stop
9)
Steps:
1. start
2. Read n
3. sum=0
4. sum=sum+(n%10)
5. n=n/10
6. if(n>0) then goto step4
7. print sum
8. stop
10)
Steps
1 .start
2. Read n
3. count=0
4. n=n/10
5. count=count+1
6. if (n>0) then goto srtp4
7. print count
8. stop
Introduction to C :
History of C Language:
In 1960's COBOL was being used for commercial
applications and FORTRAN is used 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 popular , because it seemed
too general. To reduce these generality a new
language CPL(combined programming language) was
developed at Cambridge University. It has very less
features. Then some other features were added to
this language and a new language called BCPL(Basic
combined programming language) developed by
"Martin Richards" at Cambridge University. Then " B "
language was developed by Ken Thompson at
AT&T BELL labs.
Features of C Language:
1. C is a structured programming language
with fundamental flow control construction.
2 . C is simple and versatile language.
Important points:
1 . C was basically designed for Unix
operating system. 93% of instructions,
which are written in C.
2 . C is case sensitive programming
languae. C statements are entered in
lower case letters only.
3 . C is function oriented programming
language. Any C program contains one or
more functions . Minimum One function is
compulsory by the name called main.
Without main we cant execute a C
program.
4 . Every C statement must be terminated
by semicolon ( ; ), except pre-processor
statements and function definition.
5 . A function is represented by function
name with a pair of parenthesis ( ).
[ Document section ]
Preprocessor section
(or)
Link section
main( )
{
[ Local declaration section ]
Statements
}
Document section:
Comments:
Unexecutable lines in a program are called as
comments. These lines are skipped by the compiler.
/*---------------------
---------------------
--------------------*/ Multi line comment.
Preprocessor statements:
#include:
Syntax:
1)
How to open a C editor(windows xp):
5) Compile Program ,
goto Compile menu Compile
Shortcut Keys:
Open : F3
Save : F2
Close file : Alt + F3
Full Screen : F5
Compile : Alt + F9
Run : Ctrl + F9
Output : Alt + F5
Change to another file: F6
Help : Ctrl + F1
Tracing : F7
Quit : Alt + X
printf :
Syntax:
format string
/* First Program */
#include<stdio.h>
#include<conio.h>
void main()
{
printf(Welcome to C Prograsmming);
}
clrscr :
It clears text mode window.
syntax:
void clrscr( );
getch:
It is a function and it gets a character from standard
input device(keyboard), but it doesnot echo(print) to the
screen.
Program :
/* Second Program */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf(BDPS COMPUTER EDUCATIONS);
getch( );
}
\n - new line
\t - horizontal tab(default 8 spaces)
\v - vertical tab(default 1 line)
\b - back space
\a - alert(beep sound)
\r - Carriage return
\f - form feed
\0 - null
\" - double quotes
etc.
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
printf(Welcome\n);
printf(Good Morning);
}
Output:
Welcome
Good Morning
Program : esc_b.c
#include<stdio.h>
#include<conio.h>
void main()
{
printf(Welcome\b);
printf(Good Morning);
}
Output:
WelcomGood Morning
Program : esc_r.c
#include<stdio.h>
#include<conio.h>
void main()
{
printf(Good Morning\r);
printf(Welcome);
}
Output:
Welcomerning
C Tokens
1 Identifiers
2 Keywords
3 Constants
4 Operators
5 Special characters
Identifiers :
Identifiers refer to the name of the variables,
functions, arrays,etc. created by the programmer, using
the combination of following characters.
1 Alphabets : A to Z (or) a to z
2 Digits : 0 to 9
3 Underscore : _
Note :
1 . The first character of an identifier must be an
alphabet or underscore ,we canot use digit.
2 . Default identifier length is 32 characters.
Keywords
Keywords are the words whose meaning has been
already explained by the compiler. That means at the time
of designing a language, some words are reserved to do
specific tasks. Such words are called as keywords (or)
reserved words. All C compilers support 32 keywords.
They are:
1. auto
2. break
3. case
4. char
5. const
6. continue
7. default
8. do
9. double
10. else
11. enum
12. extern
13. float
14. far
15. for
16. goto
17. if
18. int
19. long
20. register
21. return
22. short
23. signed
24. sizeof
25. static
26. struct
27. switch
28. typedef
29. union
30. unsigned
31. void
32. while
constants:
constants define fixed values, that donot change during
the execution of a program. C supports the following
constants.
1 Integer constants
2 Character constants
3 Real or floating constants
4 String constants
Operators:
Operator is a symbol which performs particular
operation. C supports a rich set of operators. C operators
can be classified into No of categories. They include
arithmetic operators, logical operators, bitwise operators,
etc.
Special characters:
Data types in C
Datatype:
It is a data storage format that can
contain a specific type
or range of values
(or)
It is a classification identifying one of
various typese of data,that determines the
possible values for that type.
The kind of data that variables may hold in a
programming language are called as data
types. C data types can be classifies into 3
categories.
1 Primary data types
2 Derived data types
3 User defined data types
char %c 1 Byte
-128 to 127
int %d 2 Bytes
-32768 to 32767
2147483647
float %f 4 Bytes
3.4*(10 power -38)
to
to
to
%o Octal Base
%x Hexa decimal base
%p Memory address
Variable:
A quantity which may vary during the execution of a
program is called as variable.
Declaration of a Variable:
datatype identifier ;
(or)
datatype identifier-1,identifier -2,,identifier-n ;
Eg:
int n;
char ch;
float f;
double db;
int a,b,c,d;
char ch1,ch2,ch3;
Initialization of variable :
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int n=100;
clrscr();
printf(%d,n);
printf(\nvalue of n = %d,n);
getch();
}
Output
100
value of n=100
Note:
In C language, all declarations will be done before the
first executable statement.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n=18;
char c=R;
float f=17.148;
double d=1714.1418;
clrscr();
printf(n=%d,n);
printf(\nc=%c,c);
printf(\nf=%f,f);
printf(\nd=%lf,d);
getch();
}
Output
n=100
ch='H'
ft=10.569000
db=1417.141800
Note:
#include<stdio.h>
#include<conio.h>
void main()
{
float f=12.4466;
double d=1234.56789;
clrscr();
printf(F=%f,f);
printf(D=%lf,d);
printf(F=%.2f,f);
printf(D=%.2lf,d);
getch();
}
Output
F=12.4466
D=1234.56789
F=12.45
D=1234.57
Constants:
Constants in C refer to fixed valued that donot
change during the execution of a program.
const:
It is a keyword and is used to declare constants.
Syntax:
const datatype identifier=value;
Or
const datatype identifier-1=value,.,identifier-n=value;
Eg:
const int a=100;
const int a=10,b=20,c=30;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
const int a=100;
clrscr();
printf(a=%d,a);
/* a=200;*/
printf(\na=%d,a);
getch();
}
Output
a=100
a=100
Symbolic constants:
#define :
It is a preprocessor statement and is used to
define symbolic constants.
Syntax :
#define identifier value
Eg : #define pi 3.14
#define g 9.8
Example:
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define g 9.8
#define val 100
void main()
{
clrscr();
printf(pi = %.2f,pi);
printf(g = %.21,g);
printf(val = %d,val);
getch();
}
Output :
PI=3.14
G=9.8
VAL=100
scanf :
It is a function and is used to read data from the standard
input device(KeyBoard).
Syntax:
int scanf(format(s),address-1,address-2,..address-n);
eg :
int n;
address of n=&n
scanf(%d,&n);
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(Enter any value:);
scanf(%d,&n);
printf(Given value : %d,n);
getch();
}
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
char c;
float f;
double d;
clrscr();
printf(Enter any character value:);
scanf(%c,&c);
printf(Enter any Int value :);
scanf(%d,&n);
printf(Enter any float value:);
scanf(%f,&f);
printf(Enter any double value:);
scanf(%lf,&d);
printf(Given Int :% d\n,n);
printf(Given char :%c\n,c);
printf(Given float :%f\n,f);
printf(Given double :%lf,d);
getch();
}
Skipping problem :
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
char ch;
clrscr();
printf(Enter any int :);
scanf(%d,&n);
printf(Enter any char:);
scanf(%c,&ch);
printf(\nGiven int :%d,n);
printf(\nGiven char :%c,ch);
getch();
}
Output
fflush :
It flushes the specified stream.
Syntax:
fflush(stream_name);
Eg: fflush(stdin);
flushall :
It flushes all open streams.
Syntax:
flushall();
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
char c;
clrscr();
printf(enter any number:);
scanf(%d,&n);
printf(enter any character:);
fflush(stdin); (or) flushall();
scanf(%c,&c);
printf(N=%d\n,n);
printf(C=%c\n,c);
getch();
}
String :
Declaration :
char identifier[size];
Eg : char st[20];
Initialization :
At the time of declaring a string variable, we can store
a constant string into that variable is called as
initialization.
syntax:
optional
char identifier[size]=string;
Eg :
char s[10]=WELCOME;
char st[ ]=ABCD;
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
char st[10]=Good Morning;
char s[]=Welcome;
printf(%s,st);
printf(%s,s);
getch();
}
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
char st[50];
clrscr();
printf(Enter a string :);
scanf(%s,st)
printf(Given string is :%s,st);
getch();
}
Output :
scanf(%[^\n]s,st)
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
char st[50];
clrscr();
printf(Enter a string :);
scanf(%[^\n]s,st);
printf(Given string is :%s,st);
getch();
}
gets:
Syntax :
gets(string varibale);
Eg: gets(st);
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
char st[50];
clrscr();
printf(Enter a string :);
gets(st);
printf(Given string is :%s,st);
getch();
}
Program :
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(enter any ASCII value from 0 to 255 :);
scanf(%d,&n);
printf(character of give ASCII value: %c,n);
getch();
}
Prgram :
#include<stdio.h>
#include<conio.h>
void main()
{
int d,m,y;
clrscr();
printf("Enter any date in the format dd-mm-yyyy :");
scanf("%d-%d-%d",&d,&m,&y);
printf("Given date is : %.2d-%.2d-%d",d,m,y);
getch();
}
Operators in C
Operator: It is a symbol and it performs particular
operation.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Bit-wise operators
7. Special operators
a) Ternary or Conditional operator
b) Comma operator
c) sizeof operator
Arithmetic operators:
Program : arithm.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter 2 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("\nMultiplication 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();
}
Relational operators :
These are used to test the relation between 2 values or 2
expressions. All C relational operators are binary
operators and hence it requires 2 operands.
Logical operators :
|| Logical OR
! Logical NOT
Assignment Operators :
1. Simple assignment : =
Eg : n=10
+=
-=
*=
/=
%=
etc.
Eg :
int n=10, if we want to add 5 to n then we will
give
n=n+5
(or)
n+=5, which is compound assignment.
Increment and Decrement Operators :
These operators are used to control the loops in an
effective method.
1 Increment operator :
The symbol ++ is used for incrementing by 1.
It is of 2 types.
1) ++ identifier ; prefix increment
2) identifier++ ; postfix increment
Eg :
1) int a = 10;
++a; (or) a++;
a = 11
2) int a = 10,b;
b = ++a;
a = 11
b = 11
3) int a = 10,b;
b = a++;
a = 11
b = 10
4) int x = 10
printf(%d \t %d,x,x++);
o/p:11 10
Decrement operator :
2) int a = 10,b;
b = --a;
a=9
b=9
3) int a = 10,b;
b = a--;
a=9
b = 10
4)
int x = 10
printf(%d \t% d,x,x--);
output : 9 10
Bit-wise Operators :
These operators are used for manipulation of data at bit
level.
These are classified into 2 types. Namely,
1. Bit-wise logical operators
2. Bit-wise shift operators.
B1 B2 B1 & B2 B1 | B2 B1 ^ B2
-------------------------------------------------------------------------------------------
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
Eg : int a=5,b=6;
a = 5 -> 1 0 1
b = 6 -> 1 1 0
1 0 1
1 1 0
----------------------
a&b : 1 0 0 =4
----------------------
1 0 1
1 1 0
----------------------
a|b : 1 1 1 =7
----------------------
1 0 1
1 1 0
----------------------
a^b : 0 1 1 =3
----------------------
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(Enter values int a and b :);
scanf(%d%d,&a,&b);
printf(\n a & b = %d,a&b);
printf(\n a | b = %d,a|b);
printf(\n a ^ b = %d,a^b);
getch();
}
1 0 0
Hence it became,
1 0 0 0 0
1 0 0 0 0 = 2 power 4 = 16
1 0 0
Hence it became,
1 0
then the value of c :-
1 0 = 2 power 1 = 2
Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int a=4,b,c;
clrscr();
b=a<<2;
c=a>>1;
printf(\n a=%d,a);
printf(\n b=%d,b);
printf(\n c=%d,c);
getch();
}
Special operators :
Eg :
int a=10,b=20,c;
c = a<b ? a : b;
output will be c =10
Program : max1_ter.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max,min;
clrscr();
printf("Enter 2 numbers : ");
scanf("%d%d",&a,&b);
max=a>b ? a : b;
min=a<b ? a : b;
printf("Maximim value : %d",max);
pri`ntf("\nMinimum value : %d",min);
getch();
}
Program : evod_ter.c
To check whether the given number is even or odd.
#include<stdio.h>
#include<conio.h>
void main ()
{
int n;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
n%2==0 ? printf("Given number is even") :
printf("Given number is odd");
getch();
}
Program : max2_ter.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max,min;
clrscr();
printf("Enter 3 numbers : ");
scanf("%d%d%d",&a,&b,&c);
max=a>b && a>c ? a : (b>c ? b : c);
min=a<b && a<c ? a : (b<c ? b : c);
printf("Maximim value : %d",max);
printf("\nMinimum value : %d",min);
getch();
}
2) comma operator :
Eg :
int a,b,c;
c=(a=10,b=20,a+b);
Example : comma.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
c=(a=10,b=20,2*a+b);
printf("a=%d",a);
printf("\nb=%d",b);
printf("\nc=%d",c);
getch();
}
3) sizeof operator :
Syntax :
sizeof (variable / expression / datatype);
Eg 1:
1. sizeof(int); 2
2. sizeof(float); 4
eg2:
int a,b;
sizeof(a); 2
sizeof(b); 2
sizeof(a+b); 2
Example : 1 sizeof_1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
char c;
float f;
double d;
clrscr();
printf("size of int : %d bytes",sizeof(n));
printf("\nsize of char : %d bytes",sizeof(c));
printf("\nsize of float : %d bytes",sizeof(f));
printf("\nsize of double : %d bytes",sizeof(d));
getch();
}
Example : 2 sizeof_2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Size of a : %d bytes",sizeof(a));
printf("\nSize of b : %d bytes",sizeof(b));
printf("\nSize of a+b : %d bytes",sizeof(a+b));
getch();
}
Precedence of Operators :
[] Array subscript
+ Unary plus
- Unary minus
& address
3 Multiplicative * Multiply
/ Divide
% Remainder(modulus)
- Binary minus(subtraction)
7 Equality == Equal to
!= Not equal to
10 | Bit wise OR
12 || Logical OR
*= Assign product
/= Assign quotient
%= Assign remainder
+= Assign sum
-= Assign difference
15 Comma , Evaluate
Type casting (or) Type conversion :
Eg :
int a,b;
float c,d;
a=5;
b=2;
c=a/b; c=2.00 Automatic (or) implicit conversion
Example : typecast.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
float c,d;
clrscr();
printf("Enter 2 numbers : ");
scanf("%d%d",&a,&b);
c=a/b;
d=(float)a/b;
printf("c=%.2f",c);
printf("\nd=%.2f",d);
getch();
}
Program : tri_area.c
#include<stdio.h>
#include<conio.h>
void main()
{
float b,h,area;
clrscr();
printf("Enter base of triangle : ");
scanf("%f",&b);
printf("Enter height of triangle : ");
scanf("%f",&h);
area=(float)1/2*b*h; /* or area=0.5*b*h; */
printf("Area of triangle : %.2f square units",area);
getch();
}
Program : circl_ar.c
#include<stdio.h>
#include<conio.h>
#define pi 3.14
void main()
{
float r,area;
clrscr();
printf("Enter radius of circle : ");
scanf("%f",&r);
area=pi*r*r;
printf("Area of circle : %.2f square units",area);
getch();
}
Program : simp_int.c
Program : swap1.c
Program : swap2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter 2 numbers : ");
scanf("%d%d",&a,&b);
printf("\nBefore swapping ");
printf("\na=%d",a);
printf("\nb=%d\n\n",b);
a=a+b;
b=a-b;
a=a-b;
printf("After swapping ");
printf("\na=%d",a);
printf("\nb=%d",b);
getch();
}
Example : compd1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100;
clrscr();
{
int b=200;
printf("Inside Compound Statement\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
}
printf("\nOutside Compound Statement\n");
printf("a=%d\n",a);
// printf("%d",b); --> not accessible outside compound
statement //
getch();
}
Example : compd2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100;
clrscr();
printf("Outside Compound Statement\n");
printf("a=%d\n\n",a);
{
int a=200;
printf("Inside Compound Statement\n");
printf("a=%d\n\n",a);
}
printf("Outside Compound Statement\n");
printf("a=%d\n",a);
getch();
}
Program : cur_bill.c
#include<stdio.h>
#include<conio.h>
void main()
{
int cno,pmr,lmr,tu;
char cname[20];
float tamt;
clrscr();
printf("Enter Consumer number : ");
scanf("%d",&cno);
printf("Enter Consumer name : ");
fflush(stdin);
gets(cname);
printf("Enter present month reading: ");
scanf("%d",&pmr);
printf("Enter last month reading : ");
scanf("%d",&lmr);
tu=pmr-lmr;
tamt=tu*4.00;
clrscr();
printf("Consumer Number : %d",cno);
printf("\nConsumer Name : %s",cname);
printf("\nPresent month reading : %d",pmr);
printf("\nLast month reading : %d",lmr);
printf("\nTotal number of units : %d",tu);
printf("\nTotal Bill Amount : %.2f",tamt);
getch();
}
Program : student.c
1) simple if statement
2) if-else statement
3) Nested if statement
4) else-if ladder statement
5) switch statement
simple if statement :
Syntax :
if( expr )
{
statements;
}
flowchart
Note :
In any control statement, the statement block contains
only a single statement, curly braces are not necessary.
Example : sim_if1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("Enter any two values : ");
scanf("%d%d",&a,&b);
max=a;
if(max<b)
{
max=b;
}
printf("Maximum Value : %d",max);
getch();
}
Example : sim_if2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter 3 numbers : ");
scanf("%d%d%d",&a,&b,&c);
max=a;
if(max<b)
max=b;
if(max<c)
max=c;
printf("Maximum Value : %d",max);
getch();
}
Example : age.c
#include<stdio.h>
#include<conio.h>
void main()
{
int cd,cm,cy,bd,bm,by,d,m,y;
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);
d=cd-bd;
m=cm-bm;
y=cy-by;
if(d<0)
{
d=d+30;
m--;
}
if(m<0)
{
m=m+12;
y--;
}
printf("Present age is : %d years %d months %d
days",y,m,d);
getch();
}
if-else statement :
Syntax :
if(expr)
{
Statements-1;
}
else
{
Statements-2;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
if(n%2==0)
printf("Given number is Even");
else
printf("Given number is Odd");
getch();
}
Nested if statements :
Form : 1
if(expr-1)
{
if(expr-2)
{
.
if(expr-n)
{
statements;
}
...
}
}
Form : 2
if(expr-1)
{
if(expr-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
if(expr-3)
{
Statement-3;
}
else
{
Statement-4;
}
}
Example : nest_if.c
To find maximum of 3 numbers using nested if
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
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("Maximum value : %d",max);
getch();
}
else-if ladder :
Syntax :
if(expr-1)
{
Statements-1;
}
else if(expr-2)
{
Statement-2;
}
..
..
else if(expr-n)
{
Statement-n;
}
else
{
else block statements;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
printf("Enter any three numbers : ");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
max=a;
else if(b>c)
max=b;
else
max=c;
printf("Maximum value : %d",max);
getch();
}
Example : ck_char.c
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character : ");
scanf("%c",&ch);
Example : vow_cons.c
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character : ");
scanf("%c",&ch);
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
{
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 a vowel");
else
printf("Given character is a consonant");
}
else
printf("Given character is not an Alphabet");
getch();
}
Example : st_det.c
Example : ndays.c
exit : <process.h>
It terminates the program.
Example : cbill.c
Units rate/unit
0 50 1.45(min)
51-100 2.80
101-200 3.05
201-300 4.75
>300 5.50
#include<stdio.h>
#include<conio.h>
void main()
{
int cno,pmr,lmr,tu;
char cname[20];
float bamt;
clrscr();
printf("Enter consumer number : ");
scanf("%d",&cno);
printf("Enter consumer name :");
fflush(stdin);
gets(cname);
printf("Enter present month reading :");
scanf("%d",&pmr);
printf("Enter last month reading :");
scanf("%d",&lmr);
if(pmr<lmr)
{
printf("Invalid reading");
getch();
exit(0);
}
tu=pmr-lmr;
if(tu<=50)
bamt=50*1.45;
else if(tu<=100)
bamt=50*1.45+(tu-50)*2.80;
else if(tu<=200)
bamt=(50*1.45)+(50*2.80)+(tu-100)*3.05;
else if(tu<=300)
bamt=(50*1.45)+(50*2.80)+(100*3.05)+(tu-200)*4.75;
else
bamt=(50*1.45)+(50*2.80)+(100*3.05)+(100*4.75)+
(tu-300)*5.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("\nTotal Bill Amount : %.2f",bamt);
getch();
}
Example : emp_sal.c
To enter emp number, name, grade, basic salary.
Calculate and display HRA,DA,TA,IT,PF,gross
salary,deductions and net salary by the following table.
A >5000 20 25 8
5 12
B <=3000 8 10 12
0 4
B >5000 15 18 5
4 10
#include<stdio.h>
#include<conio.h>
void main()
{
int eno;
char ename[20],gr;
float basic,hra,da,ta,it,pf,gs,ded,ns;
clrscr();
printf("Enter Employee Number : ");
scanf("%d",&eno);
printf("Enter Employee Name : ");
fflush(stdin);
gets(ename);
printf("Enter Employee Grade : ");
scanf("%c",&gr);
if(gr=='A' && gr=='B' && gr=='a' && gr=='b')
{
printf("Invalid Grade");
getch();
exit(0);
}
printf("Enter Basic Salary : ");
scanf("%f",&basic);
if(gr=='a' || gr=='A')
{
if(basic<=2000)
{
hra=basic*10/100;
da=basic*15/100;
ta=basic*3/100;
it=0;
pf=basic*5/100;
}
else if(basic<=5000)
{
hra=basic*15/100;
da=basic*20/100;
ta=basic*5/100;
it=basic*3/100;
pf=basic*8/100;
}
else
{
hra=basic*20/100;
da=basic*25/100;
ta=basic*8/100;
it=basic*5/100;
pf=basic*12/100;
}
}
else
{
if(basic<=3000)
{
hra=basic*8/100;
da=basic*10/100;
ta=basic*2/100;
it=0;
pf=basic*4/100;
}
else if(basic<=5000)
{
hra=basic*10/100;
da=basic*12/100;
ta=basic*4/100;
it=basic*2/100;
pf=basic*8/100;
}
else
{
hra=basic*15/100;
da=basic*18/100;
ta=basic*5/100;
it=basic*4/100;
pf=basic*10/100;
}
}
gs=basic+hra+da+ta;
ded=it+pf;
ns=gs-ded;
clrscr();
printf("\t\t\t EMPLOYEE DETAILS \n\n");
printf("\nEmployee Number : %d",eno);
printf("\nEmployee Name : %s",ename);
printf("\nEmployee Grade : %c",gr);
printf("\nBasic Salary : %.2f",basic);
printf("\nHouse Rent Allowance : %.2f",hra);
printf("\nDearness Allowance : %.2f",da);
printf("\nTravelling Allowance : %.2f",ta);
printf("\nIncome tax : %.2f",it);
printf("\nProvident Fund : %.2f",pf);
printf("\nGross Salary : %.2f",gs);
printf("\nDeductions : %.2f",ded);
printf("\nNet Salary : %.2f",ns);
getch();
}
Program : dealer.c
N 50.75 31.85
22.15
S 49.85 30.25
21.50
W 52.35 33.75
24.65
E 51.45 32.15
23.75
#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 : ");
fflush(stdin);
scanf("%c",®);
if(reg>=97 && reg<=122)
reg=reg-32; // this is to convert lower case letters to
upper case letters //
if(reg!='N' && reg!='W' && reg!='S' && reg!='E')
{
printf("Invalid Region");
getch();
exit(0);
}
printf("Enter number of litres of petrol sold : ");
scanf("%d",&np);
printf("Enter number of litres of diesel sold : ");
scanf("%d",&nd);
printf("Enter number of litres of kerosene sold : ");
scanf("%d",&nk);
if(reg=='N')
{
pa=np*50.75;
da=nd*31.85;
ka=nk*22.15;
}
else if(reg=='S')
{
pa=np*49.85;
da=nd*30.25;
ka=nk*21.50;
}
else if(reg=='W')
{
pa=np*52.35;
da=nd*33.75;
ka=nk*24.65;
}
else
{
pa=np*51.45;
da=nd*32.15;
ka=nk*23.75;
}
clrscr();
ta=pa+da+ka;
printf("Dealer Number : %d",dno);
printf("\nDealer Name : %s",dname);
printf("\nDealer Region : %c",reg);
printf("\nLitres of petrol sold : %d",np);
printf("\nLitres of deesel sold : %d",nd);
printf("\nLitres of keroene sold : %d",nk);
printf("\nPetrol Amount :%.2f",pa);
printf("\nDeesel Amount :%.2f",da);
printf("\nKerosene Amount :%.2f",ka);
printf("\nTota l Amount :%.2f",ta);
getch();
}
Switch statement :
switch(variable / expression)
{
case value-1 :
statements 1;
break;
case value-2 :
statements 2;
break;
..
.
case value-n :
statements n;
break;
default :
default statements;
}
break :
Syntax : break;
Note :
Program : switch_1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,opt;
clrscr();
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
printf("1-Addition\n2-Subtraction\n3-Multiplication\n4-
Division
\n5-Modulus\nEnter your
option : ");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("Addition of %d and %d is %d",a,b,a+b);
break;
case 2:
printf("Subtraction of %d and %d is %d",a,b,a-b);
break;
case 3:
printf("Multiplication of %d and %d is
%d",a,b,a*b);
break;
case 4:
printf("Division of %d and %d is %.2f",a,b,
(float)a/b);
break;
case 5:
printf("Modulus of %d and %d is %d",a,b,a%b);
break;
default:
printf("Invalid Option");
}
getch();
}
Program : switch_2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
char opt;
clrscr();
printf("Enter 2 numbers : ");
scanf("%d%d",&a,&b);
printf("A-Addition\nS-Subtraction\nM-
Multiplication\nD-Division
\nR-Modulus\nEnter your option : ");
fflush(stdin);
scanf("%c",&opt);
switch(opt)
{
case 'A':
case 'a':
case 'S':
case 's':
printf( "Subtraction of %d and %d is %d",a,b,a-b);
break;
case 'M':
case 'm':
printf("Multiplication of %d and %d is
%d",a,b,a*b);
break;
case 'D':
case 'd':
printf("Division of %d and %d is %d",a,b,a/b);
break;
case 'R':
case 'r':
printf("Modulus of %d and %d is %d",a,b,a%b);
break;
default:
printf("Invalid Option");
}
getch();
}
Program : ele_bill.c
Commercial Purpose
Units Rate/Unit
0 - 50 3.95(min)
>50 6.20
Extras :
service chrge:
Domestic Purpose
Units Rate/Unit
0 - 50 1.45(min)
51 - 100 2.80
>300 5.50
Extras :
service charge:
#include<stdio.h>
#include<conio.h>
void main()
{
int cno,pmr,lmr,tu,opt,ph;
char cname[20];
float pt,sc,bamt,tamt;
clrscr();
printf("\t\tMENU\n\n");
printf("---------------------");
printf("\n1-Domestic Prupose\n");
printf("\n2-Commerical Purpose\n");
printf("\nEnter your option(1 or 2) : ");
scanf("%d",&opt);
if(opt!=1 && opt!=2)
{
printf("\n\t\tInvalid Option");
getch();
exit(0);
}
printf("\nEnter Phase Type(1 or 3)");
scanf("%d",&ph);
if(ph!=1 && ph!=3)
{
printf("\n\t\tInvalid Phase");
getch();
exit(0);
}
clrscr();
printf("\nEnter Consumer Number : ");
scanf("%d",&cno);
printf("\nEnter Consumer Name : ");
fflush(stdin);
gets(cname);
printf("\nEnter Present Month Reading : ");
scanf("%d",&pmr);
printf("\nEnter Last Month Reading : ");
scanf("%d",&lmr);
if(lmr>pmr)
{
printf("\n\t\tInvalid Reading");
getch();
exit(0);
}
tu=pmr-lmr;
switch(opt)
{
case 1:
if(tu<=50)
bamt=50*1.45;
else if(tu<=100)
bamt=(50*1.45)+(tu-50)*2.80;
else if(tu<=200)
bamt=(50*1.45)+(50*2.80)+(tu-100)*3.05;
else if(tu<=300)
bamt=(50*1.45)+(50*2.80)+(100*3.05)+(tu-
200)*4.75;
else
bamt=(50*1.45)+(50*2.80)+(100*3.05)+(100*4.75)+
(tu-300)*5.50;
pt=0.06*tu;
if(ph==1)
sc=10.00;
else
sc=20.00;
break;
case 2:
if(tu<=50)
bamt=50*3.95;
else
bamt=(50*3.95)+(tu-50)*6.20;
pt=0.06*tu;
if(ph==1)
sc=20.00;
else
sc=50.00;
break;
}
tamt=bamt+pt+sc;
clrscr();
printf("\t\t\t Consumer Details\n ");
printf("-------------------------------------------------\n");
printf("\nConsumer Number : %d",cno);
printf("\nConumer Name : %s",cname);
printf("\nPresent Month Reading : %d",pmr);
printf("\nLast Month Reading : %d",lmr);
printf("\nTotal Units : %d",tu);
printf("\nPower Tax : %.2f",pt);
printf("\nService Charge : %.2f",sc);
printf("\nBill Amount : %.2f",bamt);
printf("\nTotal Amount : %.2f",tamt);
getch();
}
Syntax :
break;
continue :
It passed the control
Syntax :
continue;
goto :
Syntax of label :
identifier :
Program : nat_goto.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter a number :");
scanf("%d",&n);
printf("Natural Numbers from 1 to %d :",n);
lb:
printf("\t%d",i);
i++;
if(i<=n)
goto lb;
getch();
}
Program : goto1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter value of n :");
scanf("%d",&n);
if(n==1)
goto lb1;
if(n==2)
goto lb2;
printf("\nWelcome");
lb1:
printf("\nLabel 1");
lb2:
printf("\nLabel 2");
getch();
}
Program : goto2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
if(n==1)
goto lb1;
if(n==2)
goto lb2;
printf("\nWelcome");
goto lb;
lb1:
printf("\nLabel 1");
goto lb;
lb2:
printf("\nLabel 2");
lb:
getch();
}
gotoxy :
x - cols
y - rows
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
gotoxy(35,12);
printf("WELCOME");
getch();
}
Program : st_formt.c
-----------------------------------------------------------------
BDPS SOFTWARE LIMITED
VIJAYAWADA
-----------------------------------------------------------------
SID : SNAME :
MARKS IN C :
MARKS IN CPP :
MARKS IN JAVA :
#include<stdio.h>
#include<conio.h>
void main()
{
int sid,c,cpp,java,tot;
char sname[20];
float avg;
clrscr();
gotoxy(15,3);
printf("------------------------------------------------");
gotoxy(28,5);
printf("BDPS SOFTWARE LIMITED");
gotoxy(33,7);
printf("VIJAYAWADA");
gotoxy(15,9);
printf("------------------------------------------------");
gotoxy(15,11);
printf("SID : ");
gotoxy(40,11);
printf("SNAME : ");
gotoxy(15,14);
printf("MARKS IN C : ");
gotoxy(15,16);
printf("MARKS IN CPP : ");
gotoxy(15,18);
printf("MARKS IN JAVA : ");
gotoxy(15,21);
printf("TOTAL MARKS : ");
gotoxy(40,21);
printf("AVERAGE : ");
gotoxy(15,23);
printf("RESULT : ");
gotoxy(40,23);
printf("DIVISION : ");
gotoxy(15,25);
printf("------------------------------------------------");
gotoxy(21,11);
scanf("%d",&sid);
gotoxy(51,11);
fflush(stdin);
gets(sname);
lb1:
gotoxy(31,14);
scanf("%d",&c);
if(c>100)
{
gotoxy(30,30);
printf("Invalid Marks of C");
getch();
gotoxy(30,30);
printf(" ");
gotoxy(31,14);
printf(" ");
goto lb1;
}
lb2:
gotoxy(31,16);
scanf("%d",&cpp);
if(cpp>100)
{
gotoxy(30,30);
printf("Invalid Marks of CPP");
getch();
gotoxy(30,30);
printf(" ");
gotoxy(31,16);
printf(" ");
goto lb2;
}
lb3:
gotoxy(31,18);
scanf("%d",&java);
if(java>100)
{
gotoxy(30,30);
printf("Invalid Marks of Java");
getch();
gotoxy(30,30);
printf(" ");
gotoxy(31,18);
printf(" ");
goto lb3;
}
tot=c+cpp+java;
avg=(float)tot/3;
gotoxy(31,21);
printf("%d",tot);
gotoxy(51,21);
printf("%.2f",avg);
if(c>=50 && cpp>=50 && java>=50)
{
gotoxy(31,23);
printf("PASS");
gotoxy(51,23);
if(avg>=60)
printf("FIRST");
else
printf("SECOND");
}
else
{
gotoxy(31,23);
printf("FAIL");
gotoxy(51,23);
printf("NO DIVISION");
}
getch();
}
Loop control statements :
loop:
The process of repeatedly executing a block of
statement up to specified number of times is called as
loop.
1) while loop
2) do-while loop
3) for loop
Syntax :
while(test condition)
{
Statements;
}
Program : nnos_w.c
To print natural numbers from 1 to given number
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
printf("Enter a number : ");
scanf("%d",&n);
printf("Natural number from 1 to %d\n\n",n);
while(i<=n)
{
printf("\t%d",i);
i++;
}
getch();
}
Program : ev_od_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf("Enter a number : ");
scanf("%d",&n);
printf("\n\nEven numbers from 1 to %d\n\n",n);
i=1;
while(i<=n)
{
if(i%2==0)
printf("\t%d",i);
i++;
}
printf("\n\n\nOdd numbers from 1 to %d\n\n",n);
i=1;
while(i<=n)
{
if(i%2==1) // if(i%2!=0)
printf("\t%d",i);
i++;
}
getch();
}
Program : nsum_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1,sum=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("Sum of %d natural numbers is %d",n,sum);
getch();
}
Note :
We can also find the sum of n digits by the following
formula :
Sum = n * (n+1)/2
Program : facts_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("\n\nFactors of given number : \n\n");
while(i<=n)
{
if(n%i==0)
printf("\t%d",i);
i++;
}
getch();
}
Program : facto_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
unsigned long fact=1;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
while(n>=1)
{
fact=fact*n;
n--;
}
printf("\n\nFactorial of %d is %lu ",n,fact);
getch();
}
Program : ndig_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int count=0;
unsigned long n;
clrscr();
printf("Enter a number : ");
scanf("%lu",&n);
while(n>0)
{
n=n/10;
count++;
}
printf("\n\nNumber of digits of given number : %d
",count);
getch();
}
Program : sumdig_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0;
unsigned long n;
clrscr();
printf("Enter a number : ");
scanf("%lu",&n);
while(n>0)
{
sum=sum+(n%10);
n=n/10;
}
printf("\n\nSum of digits of given number : %d ",sum);
getch();
}
Program : rev_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
unsigned long rev=0;
printf("Enter a number : ");
scanf("%d",&n);
while(n>0)
{
rev=(rev*10)+(n%10);
n=n/10;
}
printf("Reverse number of given number : %lu",rev);
getch();
}
Program : sum_dig1.c
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long n;
int sum=0;
printf("Enter a number : ");
scanf("%d",&n);
while(n>0)
{
sum=sum+(n%10);
n=n/10;
}
printf("Sum of digits : %d",sum);
getch();
}
Program : sum_dig2.c
To find sum of digits of given number
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long n;
int sum=0;
printf("Enter a number : ");
scanf("%lu",&n);
while(n>0)
{
sum=sum+(n%10);
n=n/10;
if(n==0 && sum>9)
{
printf("\n%d\n",sum);
n=sum;
sum=0;
}
}
printf("Sum of digits : %d",sum);
getch();
}
Note :
Program : rev1_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,count=0;
unsigned long rev=0;
printf("Enter a number : ");
scanf("%d",&n);
while(n>0)
{
rev=(rev*10)+(n%10);
n=n/10;
count++;
}
printf("Reverse number of given number :
%*lu",count,rev);
getch();
}
Program : pal_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,rev=0;
printf("Enter a number : ");
scanf("%d",&n);
m=n;
while(m>0)
{
rev=(rev*10)+(m%10);
m=m/10;
}
if(n==rev)
printf("Given number is a Palindrome");
else
printf("Given number is not Palindrome");
getch();
}
Program : prime_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1,count=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
while(i<=n)
{
if(n%i==0)
count++;
i++;
}
if(count==2)
printf("Given number is Prime");
else
printf("Given numbr is not Prime");
getch();
}
Program : fibo_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,a=1,b=0,c=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Fibonacci series :");
while(n>=1)
{
printf("\t%d",c);
c=a+b;
a=b;
b=c;
n--;
}
getch();
}
Program : ev_od1_w.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=2,k=1;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
while(k<=2)
{
if(i==2)
printf("Even numbers from 1 to %d",n);
if(i==1)
printf("Odd numbers from 1 to %d",n);
printf("%d\t",i);
i=i+2;
if(i>n)
{
i=1;
k++;
}
}
}
Syntax :
do
{
Statements;
}
while(test condition) ;
Program : nat_dw.c
Programs to display natural number from 1 to given
number is using do-while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("\nNatural numbers from 1 to %d :",n);
do
{
printf("\t%d",i);
i++;
} while(i<=n);
getch();
}
for loop :
It is the most commonly used loop statement in C
language. It is consisting of 3 expressions.
Syntax :
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("\nNatural numbers from 1 to %d\n\n",n);
for(i=1;i<=n;i++)
{
printf("\t%d",i);
}
getch();
}
Program : rev_for.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
unsigned long rev;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(rev=0;n>0;n=n/10)
{
rev=(rev*10)+(n%10);
}
printf("Reverse number of given number : %lu",rev);
getch();
}
Program : perfect.c
To check whether the given number is perfect number
or not
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,sum=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=n/2;i++)
{
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("Given number is Perfect number");
else
printf("Given number is not Perfect number");
getch();
}
Perfect number :
Program : armst.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,m,r;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
m=n;
while(m>0)
{
r=m%10;
sum=sum+(r*r*r);
m=m/10;
}
if(n==sum)
printf("Given number is Armstrong number");
else
printf("Given number is not Armstrong number");
getch();
}
Program : table.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=20;i++)
{
printf("\n%d * %d = %d",n,i,n*i);
}
getch();
}
Program : continue.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0;
clrscr();
while(i<100)
{
i++;
if(i==40 || i==50 || i==60)
continue;
printf("%d\t",i);
}
getch();
Program : gcd.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,g,i;
clrscr();
printf("Enter 2 numbers : ");
scanf("%d%d",&a,&b);
for(i=1;i<=a && i<=b;i++)
{
if(a%i==0 && b%i==0)
g=i;
}
printf("GCD of given numbers : %d",g);
getch();
}
Eg :
GCD of 10 and 20 = 10
10%10 = 0 and 20%10 = 0 also (10,20)%2 = 0 and
(10,20)%5 = 0, but the greatest of 2, 5 and 10 is 10.
Hence GCD = 10.
Program : lcm.c
Eg :
LCM of 10 and 15 is 30
30%10 = 0 and 30%10 = 0
2 nd Method
------------------
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,lcm;
clrscr();
printf("Enter any two numbers :");
scanf("%d%d",&a,&b);
if(a>b)
lcm=a;
else
lcm=b;
Nested loops :
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,count;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Prime Numbers for 1 to %d\n",n);
for(i=1;i<=n;i++)
{
count=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
count++;
}
if(count==2)
printf("\t%d",i);
}
getch();
}
Program : prm2_nl.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,i,j,count;
clrscr();
printf("Enter starting number : ");
scanf("%d",&n1);
printf("Enter ending number : ");
scanf("%d",&n2);
for(i=n1;i<=n2;i++)
{
count=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
count++;
}
if(count==2)
printf("\t%d",i);
}
getch();
}
Program : pal_nl.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,rev,m,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
rev=0;
m=i;
while(m>0)
{
rev=(rev*10)+(m%10);
m=m/10;
}
if(rev==i)
printf("\t%d",i);
}
getch();
}
Program : perf_nl.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,sum=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Perfect Numbers between 1 and %d : ",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("\t%d",i);
}
getch();
}
Program : armst_nl.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,r,arm,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Armstrong numbers from 1 to %d : \n",n);
for(i=1;i<=n;i++)
{
arm=0;
m=i;
while(m>0)
{
r=m%10;
arm=arm+(r*r*r);
m=m/10;
}
if(arm==i)
printf("\t%d",i);
}
getch();
}
Program : prm_fact.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Prime Factor of %d : \n",n);
while(n>1)
{
i=2;
while(1)
{
if(n%i==0)
{
printf("\t%d",i);
n=n/i;
break;
}
else
i++;
}
}
getch();
}
Integer :
1. int n=100
printf(%d,n);
Output : 100
2. int n=100
printf(%5d,n);
Output : 100
2 spaces
3. int n=100
printf(%-5d,n);
Output : 100
2 spaces
4. int n=5
printf(%.2d,n);
Output : 05
5. int n=5
printf(%.3d,n);
Output : 005
Character :
1. char c=R
printf(%c,c);
Output : R
2. char c=R
printf(%4c,c);
Output : R
3 spaces
3. char c=R
printf(%-4c,c);
Output : R
3 spaces
Float :
1. float f=14.1718
printf(%f,f);
Output : 14.171800
2. float f=14.1718
printf(%12f,f);
Output : 14.171800
3 spaces
3. float f=14.1718
printf(%-12f,f);
Output : 14.171800
3 spaces
4. float f=14.1718
printf(%.2f,f);
Output : 14.17
5. float f=14.1718
printf(%7.2f,f);
Output : 14.17
2 spaces
In 7.2, 7 indicates total number of digits including
decimal point, 2 represents number of digits after decimal
point.
String :
1. char st[10]=welcome
printf(%s,s);
Output : welcome
2. char st[10]=welcome
printf(%9s,s);
Output : welcome
2 spaces
3. char st[10]=welcome
printf(%-9s,s);
Output : welcome
2 spaces
4. char st[10]=welcome
printf(%.3s,s);
Output : wel
Output : 100
2 spaces
Program : patrn1.c
w
we
wel
welc
welco
welcom
welcome
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
char st[10]="welcome";
clrscr();
for(x=1;x<=7;x++)
{
printf("\n%.*s",x,st);
}
getch();
}
textmode() :
C40 1 Color
40 columns
C80 3 Color
80 columns
MONO 7 Monochrome
80 columns
VGA (Video
50 line
graphic adapter)
Program : txtmode1.c
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
textmode(1); // or textmode(C40);
gotoxy(17,12);
printf("RAJI");
getch();
}
Program : txtmode2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
textmode(64); // or textmode(C4350);
for(i=1;i<=45;i++)
{
printf("\nRAJI");
}
getch();
}
textcolor() :
teextbackground() :
BLACK 0 Yes
Yes
BLUE 1 Y
Y
GREEN 2 Y
Y
CYAN 3 Y
Y
RED 4 Y
Y
MAGENTA 5 Y
Y
BROWN 6 Y
Y
LIGHT GREY 7 Y
Y
DARK GREY 8 N
Y
LIGHT BLUE 9 N
Y
LIGHT GREEN 10 N
Y
LIGHT CYAN 11 N
Y
LIGHT RED 12 N
Y
LIGHT MAGENTA 13 N
Y
YELLOW 14 N
Y
WHITE 15 N
Y
cprintf() :
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
textmode(1);
textcolor(RED+BLINK);
textbackground(WHITE);
gotoxy(17,12);
cprintf("RAJI");
getch();
}
Program : patrn2.c
*****
*****
*****
*****
*****
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%2c",'*');
}
printf("\n");
}
getch();
}
Program : patrn3.c
*
**
***
****
*****
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%2c",'*');
}
printf("\n");
}
getch();
}
Program : patrn4.c
1
22
333
4444
55555
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%3d",i);
}
printf("\n");
}
getch();
}
Program : patrn5.c
1
12
123
1234
12345
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%3d",j);
}
printf("\n");
}
getch();
}
Program : patrn6.c
*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,n,s;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
s=n*2;
for(i=1;i<=n;i++)
{
/*
for(k=1;k<=s;k++)
{
printf(" ");
}
or */
printf("%*c",s,32);
for(j=1;j<=i;j++)
{
printf("%4c",'*');
}
printf("\n");
s=s-2;
}
getch();
}
Program : patrn7.c
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,n,s;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
s=n*2;
for(i=1;i<=n;i++)
{
for(k=1;k<=s;k++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("%4d",i);
}
printf("\n\n");
s=s-2;
}
getch();
}
Program : patrn8.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k=1,n,s;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
s=n*2;
for(i=1;i<=n*2;i++)
{
printf("%*c",s,32);
for(j=1;j<=k;j++)
{
printf("%4c",'*');
}
if(i<n)
{
s=s-2;
k++;
}
else
{
s=s+2;
k--;
}
printf("\n");
}
getch();
}
Program : patrn9.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,k=1;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%4d",k);
if(j<n)
{
if(i%2==0)
k--;
else
k++;
}
}
printf("\n");
k=k+n;
}
getch();
}
Program : patrn10.c
1 2 3 4 5
5 1 2 3 4
5 4 1 2 3
5 4 3 1 2
5 4 3 2 1
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,n,m;
clrscr();
printf("Enter value of n : ");
scanf("%d",&n);
m=n;
for(i=1;i<=n;i++)
{
for(j=n;j>m;j--)
{
printf("%3d",j);
}
for(k=1;k<=m;k++)
{
printf("%3d",k);
}
printf("\n");
m--;
}
getch();
}
Program : patrn11.c
To generate the following pattern
ABCDEFGFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
*/
#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();
}
Program : patrn12.c
*/
#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)
{
if(i<7)
{
x--;
y++;
}
else
{
x++;
y--;
}
}
}
getch();
}
delay() : <dos.h>
kbhit() :
_setcursortype() :
It selects cursor appearance.
Program : rajiram.c
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int c=1,c1=36,r=1;
textmode(1);
_setcursortype(_NOCURSOR);
while(!kbhit())
{
textbackground(WHITE);
clrscr();
textcolor(BLUE);
gotoxy(c,12);
cprintf("raji);
textcolor(RED);
gotoxy(c1,12);
cprintf("ram");
textcolor(MAGENTA);
gotoxy(18,r);
cprintf("WEDS");
c++;
c1--;
r++;
if(c>36)
{
c=1;
c1=36;
}
if(r>25)
r=1;
delay(150);
}
getch();
}
Functions in C
Function :
Function is a self contained block of statements and it
performs a particular task . It can be used at several times
in a program, but defined only once.
Library functions:
1. Function declaration
2. Function definition
3. Function calling
Function declaration:
Syntax:
returntype function_name ( [argument_list] ) ;
Function definition:
Syntax:
Function calling :
Syntax:
function_name ( [parameter_list] );
Note:
The arguments which are given at the time of function
declaration or function definition are called as arguments
or formal arguments. The arguments which are given at
the time of function calling are called as parameters or
actual arguments.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
void func(); // declaration
clrscr();
func(); // calling
getch();
}
return(keyword):
Syntax:
return [expr] ;
Example : ret_max.c
#include<stdio.h>
#include<conio.h>
void main()
{
int maxval(int,int);
int a,b,m;
clrscr();
printf("Enter any two numbrs : ");
scanf("%d%d",&a,&b);
m=maxval(a,b);
printf("Maximum Value : %d",m);
getch();
}
int maxval(int x,int y)
{
if(x>y)
return x;
else
return y;
}
Example : cat1.c
#include<stdio.h>
#include<conio.h>
void main()
{
void sum();
clrscr();
sum();
getch();
}
void sum()
{
int a,b;
printf(Enter any two numbers:);
scanf("%d%d",&a,&b);
printf(sum= %d,a+b);
}
#include<stdio.h>
#include<conio.h>
void main()
{
void sum(int,int);
int a,b,s;
clrscr();
printf(Enter any two numbers :);
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
void sum(int x,int y)
{
printf(sum= %d,x+y);
}
Example : cat3.c
#include<stdio.h>
#include<conio.h>
void main()
{
int sum(int,int);
int a,b,s;
clrscr();
printf(Enter any two numbers :);
scanf("%d%d",&a,&b);
s=sum(a,b);
printf(sum= %d,s);
getch();
}
int sum(int x,int y)
{
return x+y;
}
Example : cat4.c
#include<stdio.h>
#include<conio.h>
void main()
{
int sum();
int s;
clrscr();
s=sum();
printf("sum = %d",s);
getch();
}
int sum()
{
int a,b;
printf(Enter any two numbers:);
scanf("%d%d",&a,&b);
return a+b;
}
Program : fn_max.c
#include<stdio.h>
#include<conio.h>
void main()
{
int maxval(int,int);
int a,b,c,m;
clrscr();
printf("Enter 3 numbrs : ");
scanf("%d%d%d",&a,&b,&c);
m=maxval(a,b);
m=maxval(m,c);
printf("Maximum Value : %d",m);
getch();
}
int maxval(int x,int y)
{
if(x>y)
return x;
else
return y;
}
Program : nnos_fn.c
Program : fact_fn.c
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int n;
unsigned long f;
clrscr();
printf("Entr a number : ");
scanf("%d",&n);
f=fact(n);
printf("Factorial of %d : %lu",n,f);
getch();
}
unsigned long fact(int x)
{
unsigned long f=1;
while(x>=1)
{
f=f*x;
x--;
}
return f;
}
Program : rev_fn.c
Program : fibo_fn.c
#include<stdio.h>
#include<conio.h>
void main()
{
void fibo(int);
int n;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
printf("Fibonacci series \n");
fibo(n);
getch();
}
void fibo(int x)
{
int i,a=0,b=1,c;
printf("%d\t%d",a,b);
for(i=1;i<=x-2;i++)
{
c=a+b;
printf("\t%d",c);
a=b;
b=c;
}
}
Program : lcm_gcd.c
#include<stdio.h>
#include<conio.h>
void main()
{
int lcm(int,int);
int gcd(int,int);
int l,g,a,b;
clrscr();
printf("Enter 2 numbers : ");
scanf("%d%d",&a,&b);
l=lcm(a,b);
g=gcd(a,b);
printf("LCM of %d and %d : %d\n",a,b,l);
printf("GCD of %d and %d : %d",a,b,g);
getch();
}
int lcm(int x,int y)
{
int lm;
if(x>y)
lm=x;
else
lm=y;
while(1)
{
if(lm%x==0 && lm%y==0)
break;
lm++;
}
return lm;
}
int gcd(int x,int y)
{
int gd,i;
for(i=1;i<=x && i<=y;i++)
{
if(x%i==0 && y%i==0)
gd=i;
}
return gd;
}
1
( n=0,r=0)
n values
1 1
(n=1,r=0) (n=1,r=1)
1 2 1
(n=2,r=0) (n=2,r=1) (n=2,r=2)
1 3 3
1
(n=3,r=0) (n=3,r=1) (n=3,r=2)
(n=3,r=3)
1 4 6 4
1
(n=4,r=0) (n=4,r=1) (n=4,r=2) (n=4,r=3)
(n=4,r=4)
r values
Storage classes
Program : auto1.c
#include<stdio.h>
#include<conio.h>
void main()
{
auto int a,b;
clrscr();
printf("\na = %d",a);
printf("\nb = %d",b);
getch();
}
static variables :
The memory of static variables remains unchanged
until the end of the program.
Keyword : static
Program : static1.c
#include<stdio.h>
#include<conio.h>
void main()
{
static int a,b;
clrscr();
printf("\na = %d",a);
printf("\nb = %d",b);
getch();
}
Program : static2.c
#include<stdio.h>
#include<conio.h>
void main()
{
void disp();
int i;
clrscr();
for(i=1;i<=10;i++)
{
disp();
}
getch();
}
void disp()
{
static int n=1;
printf("%d\t",n);
n++;
}
Output
1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1
external (or) global variables :
Program : extern1.c
#include<stdio.h>
#include<conio.h>
int a,b;
void main()
{
clrscr();
printf("\na = %d",a);
printf("\nb = %d",b);
getch();
}
Program : extern2.c
#include<stdio.h>
#include<conio.h>
void main()
{
extern int a;
clrscr();
printf("a = %d",a);
getch();
}
int a=100;
Note :
Note :
It supports only integral data types (int and char)
Program : register.c
#include<stdio.h>
#include<conio.h>
void main()
{
register int a,b;
clrscr();
printf("\na = %d",a);
printf("\nb = %d",b);
getch();
}
Recursive Function :
Program : nnos_rfn.c
Note :
Program : fact_rfn.c
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int n;
unsigned long f;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
f=fact(n);
printf("Factorial of %d is %lu",n,f);
getch();
}
unsigned long fact(int x)
{
if(x<=1)
return 1;
else
return x*fact(x-1);
}
Program : ncr_rfn.c
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int n,r,ncr;
printf("Enter n and r values : ");
scanf("%d%d",&n,&r);
ncr=fact(n)/(fact(n-r)*fact(r));
printf("ncr value : %d",ncr);
getch();
4c2 = 6 ( 4 * 5 ) / ( 1 * 2)
8c3 = 56 ( 8 * 7 * 6 ) / ( 1 * 2 * 3 )
Program : pascal.c
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long fact(int);
int i,j,k,n,ncr,s;
printf("Enter n value : ");
scanf("%d",&n);
s=n*2;
for(i=0;i<=n;i++)
{
/* for(k=1;k<=s;k++)
{
printf(" ");
} */
printf("%*c",s,32);
for(j=0;j<=i;j++)
{
ncr=fact(i)/(fact(i-j)*fact(j));
printf("%d ",ncr);
}
printf("\n\n");
s=s-2;
}
getch();
}
unsigned long fact(int x)
{
if(x<=1)
return 1;
else
return x*fact(x-1);
}
Program : rev_rfn.c
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long rev(int);
unsigned long r;
int n;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
r=rev(n);
printf("Reverse number : %lu",r);
getch();
}
unsigned long rev(int x)
{
static unsigned long r=0;
r=(r*10)+(x%10);
x=x/10;
if(x>0)
rev(x);
return r;
}
Note :
Progra
m : fibo_rfn.c
#include<stdio.h>
#include<conio.h>
void main()
{
void fibo(int);
int n;
printf("Enter a number : ");
scanf("%d",&n);
fibo(n);
getch();
}
void fibo(int x)
{
static int a=1,b=0,c=0;
if(x>=1)
{
printf("\t%d",c);
c=a+b;
a=b;
b=c;
fibo(x-1);
}
}
Program : mn_mn.c
Note :
Math.h Functions :
sqrt :
It Calculates the square root of a given number.
Syntax :
double sqrt(double x);
Program : sqrt.c
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n;
double s;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
s=sqrt(n);
printf("Square root of %d = %.3lf",n,s);
getch();
}
Pow :
It Calculates exponential value of given base and
power.
Syntax :
Program : power.c
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int b,p;
double e;
printf("Enter base and power values : ");
scanf("%d%d",&b,&p);
e=pow(b,p);
printf("Exponential value = %.3lf",e);
getch();
}
Program : flor_ceil.c
To find floor and ceil values of a given number
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
double n,f,c;
clrscr();
printf("Enter a number : ");
scanf("%lf",&n);
f=floor(n);
c=ceil(n);
printf("Floor Value = %.2lf",f);
printf("\nCeil Value = %.2lf",c);
getch();
}
abs :
Syntax :
int abs(int x);
Program : abs.c
#include<stdio.h>
#include<conio.h>
void main()
{
int n,a;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
a=abs(n);
printf("Given value : %d",n);
printf("\nAbsolute value : %d",a);
getch();
}
Program : triangle.c
Program : compound.c
Program : sim_ser.c
Evaluate the following simple series
1 + 1/2 + 1/3 + 1/4 + .............
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
float sum=0;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+(float)1/i;
}
printf("Sum = %.2f",sum);
getch();
}
Program : exp_ser.c
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
unsigned long fact(int);
int i,x,n;
float sum=0;
clrscr();
printf("Enter a value of x and n : ");
scanf("%d%d",&x,&n);
for(i=1;i<=n;i++)
{
sum=sum+pow(x,i)/fact(i);
}
printf("Sum = %.2f",sum);
getch();
}
unsigned long fact(int x)
{
if(x<=1)
return 1;
else
return x*fact(x-1);
}
Program : sin_ser.c
Program : cos_ser.c
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
unsigned long fact(int);
int i,n,x,p=0;
float sum=0;
clrscr();
printf("Enter value of x and n : ");
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();
}
unsigned long fact(int x)
{
if(x<=1)
return 1;
else
return x*fact(x-1);
}
int a,b,c,d,e,f;
Arrays
Types of arrays :
C supports 3 types of arrays,they are
Declaration :
datatype arr_name[size];
Eg : int a[5];
Initialization :
optional
datatype arr_name[size] = {val-1,val-2,..val-n};
Eg : int a[5]={1,2,3,4,5};
(Or)
int a[]={1,2,3,4,5,6,7};
Program : arr1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i,a[5]={1,2,3,4,5};
clrscr();
for(i=0;i<5;i++)
{
printf("\n a[%d] = %d",i,a[i]);
}
getch();
}
Program : arr2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,a[20];
clrscr();
printf("Enter number of elements : ");
scanf("%d",&n);
if(n>20)
{
printf("Invalid size");
getch();
exit(0);
}
printf("\nEnter Elements : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nGiven Elements : ");
for(i=0;i<n;i++)
{
printf("\n a[%d] = %d",i,a[i]);
}
getch();
}
Program : arr3.c
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,a[20],max,min;
clrscr();
printf("Enter number of Elements : ");
scanf("%d",&n);
printf("\nEnter Elements : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
max=min=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\nMaximum Element : %d",max);
printf("\nMinimum Element : %d",min);
getch();
}
Program : arr4.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,se,ck=0;
clrscr();
printf("Enter number of Elements : ");
scanf("%d",&n);
printf("\nEnter Elements \n\n");
for(i=0;i<n;i++)
{
printf("Enter element in 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 is found at a[%d]",se,i);
}
}
if(ck==0)
printf("%d is not found",se);
getch();
}
Program : arr5.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,j,t;
clrscr();
printf("Enter number of Elements : ");
scanf("%d",&n);
printf("\nEnter Elements : \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n\nElements Before Sorting : ");
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
// sorting //
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\n\nElements After Sorting : ");
for(i=0;i<n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
getch();
}
Program : arr6.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [],int);
void disp(int [],int);
int a[20],n;
clrscr();
printf("Enter number of elements : ");
scanf("%d",&n);
printf("Enter Elements : ");
accept(a,n);
printf("Given Elements : ");
disp(a,n);
getch();
}
void accept(int x[],int s)
{
int i;
for(i=0;i<s;i++)
{
scanf("%d",&x[i]);
}
}
void disp(int x[],int s)
{
int i;
for(i=0;i<s;i++)
{
printf("\t%d",x[i]);
}
}
Program : arr7.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int[],int);
void disp(int[],int);
void sort(int[],int);
int a[20],n;
printf("Enter number of elements : ");
scanf("%d",&n);
printf("Enter elements : ");
accept(a,n);
printf("\nElements Before Sorting :");
disp(a,n);
sort(a,n);
printf("\nElements After Sorting : ");
disp(a,n);
getch();
}
Program : arr8.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int[],int);
void disp(int[],int);
int search(int[],int,int);
int a[20],n,se,p;
printf("Enter number of elements : ");
scanf("%d",&n);
printf("Enter elements : ");
accept(a,n);
printf("\nGiven Elements :");
disp(a,n);
printf("\nEnter element to search : ");
scanf("%d",&se);
p=search(a,n,se);
if(p==-1)
printf("%d is not found",se);
else
printf("%d is found at position %d",se,p);
getch();
}
void accept(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
}
void disp(int a[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
}
int search(int a[],int n,int se)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==se)
return i;
}
return -1;
}
Eg : int a[3][3];
Elements are :
a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
Initialization :
Form : 1
optional
datatype arr_name[row size][col size]={value-
1,........,value-n};
Eg :
Form : 2
optional
datatype arr_name[row size][col size]={ {value-
1,...,value-n},
{value-
1,....,value-n},
-----------
--------------
-----------
--------------
{value-
1,....,value-n}};
Eg :
4) int a[3][3]={{1,2,3},
{4,5,6},
{7,8,9} };
1 2 3
4 5 6
7 8 9
5) int a[3][3]={{1},
{4,6},
{8,9}};
1 0 0
4 6 0
8 9 0
Program : arr11.c
#include<stdio.h>
#include<conio.h>
void main()
{
//int a[3][3]={1,2,3,4,5,6,7,8,9}; (or)
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("\na[%d][%d]=%d",i,j,a[i][j]);
}
}
getch();
}
Program : arr12.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],r,c,i,j;
clrscr();
printf("Enter number of rows and columns : ");
scanf("%d%d",&r,&c);
if(r>10 || c>10)
{
printf("Invalid Size");
getch();
exit(0);
}
printf("\nEnter Elements : ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nGiven Elements : \n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
getch();
}
Program : arr13.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][10],int,int);
void disp(int [][10],int,int);
int a[10][10],r,c;
clrscr();
printf("Enter number of rows and columns : ");
scanf("%d%d",&r,&c);
printf("\nEnter Elements : ");
accept(a,r,c);
printf("\nGiven Elements : ");
disp(a,r,c);
getch();
}
void accept(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void disp(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
Program : arr14.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][10],int,int);
void disp(int [][10],int,int);
void addt(int [][10],int[][10],int[][10],int,int);
int a[10][10],b[10][10],add[10][10],r,c;
clrscr();
printf("Enter number of rows and columns : ");
scanf("%d%d",&r,&c);
printf("\nEnter First Matrix Elements : ");
accept(a,r,c);
printf("\nEnter Second Matrix Elements : ");
accept(b,r,c);
printf("\nElements of Given First Matrix : \n");
disp(a,r,c);
printf("\nElements of Given Second Matrix : \n");
disp(b,r,c);
addt(a,b,add,r,c);
printf("\n Addition of given 2 Matrices :\n");
disp(add,r,c);
getch();
}
void accept(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void disp(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
void addt(int a[][10],int b[][10],int add[][10],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];
}
}
}
pogram : arr15.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][10],int,int);
void disp(int [][10],int,int);
void mul(int [][10],int[][10],int[][10],int,int,int);
int a[10][10],b[10][10],c[10][10],m,n,p,q;
clrscr();
printf("Enter number of rows and columns of First
Matrix : ");
scanf("%d%d",&m,&n);
printf("Enter number of rows and columns of Second
Matrix : ");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("\nMatrix Multiplication is not Possible");
getch();
exit(0);
}
printf("\nEnter First Matrix Elements : ");
accept(a,m,n);
printf("\nEnter Second Matrix Elements : ");
accept(b,p,q);
printf("\nElements of Given First Matrix : \n");
disp(a,m,n);
printf("\nElements of Given Second Matrix : \n");
disp(b,p,q);
mul(a,b,c,m,n,q);
printf("\nMultiplication of given Matrices :\n");
disp(c,m,q);
getch();
}
void accept(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void disp(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
void mul(int a[][10],int b[][10],int c[][10],int m,int n,int
q)
{
int i,j,k;
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
}
Program : arr16.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][10],int,int);
void disp(int [][10],int,int);
int checkmat(int [][10],int,int);
int a[10][10],r,c,k;
printf("Enter number of rows and columns : ");
scanf("%d%d",&r,&c);
printf("\nEnter Elements : ");
accept(a,r,c);
printf("\nGiven Elements : ");
disp(a,r,c);
k=checkmat(a,r,c);
if(k==1)
printf("Given Matrix is Indentity Matrix");
else
printf("Given Matrix is not Indentity Matrix");
getch();
}
void accept(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void disp(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
int checkmat(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(i==j)
{
if(a[i][j]!=1)
return 0;
}
else
{
if(a[i][j]!=0)
return 0;
}
}
}
return 1;
}
Program : arr17.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int [][10],int,int);
void disp(int [][10],int,int);
void trans(int [][10],int[][10],int,int);
int a[10][10],at[10][10],r,c;
clrscr();
printf("Enter number of rows and columns : ");
scanf("%d%d",&r,&c);
printf("\nEnter Elements : ");
accept(a,r,c);
printf("\nGiven Elements : \n");
disp(a,r,c);
trans(a,at,r,c);
printf("Transpose Matrix : \n");
disp(at,c,r);
getch();
}
void accept(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void disp(int a[][10],int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
void trans(int a[][10],int at[][10],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];
}
}
}
a[2][2][3]
Syntax :
Datatype arr_name [s1][s2]
[sn];
Eg : int a[2][2][3]
a[1][0][0] a[1][0][1]
a[1][0][2]
a[1][1][0] a[1][1][1]
a[1][1][2]
Program : arr18.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2][3],i,j,k;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<3;k++)
{
printf("Enter Value into a[%d][%d]
[%d] : ",i,j,k);
scanf("%d",&a[i][j][k]);
}
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<3;k++)
{
printf("\nGiven Value in a[%d][%d][%d]
= %d",i,j,k,a[i][j][k]);
}
}
}
getch();
}
Strings
A group of characters defined between
double quotation marks is a string. It is a
constant string ,But in C language, a string
variable is nothing but an array of characters
and terminated by a null character (\0).
Declaration :
Initialization :
optional
Syntax : char identifier[size] = string;
Note :
Program : str1.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[10]="WELCOME";
char str[]="ABCD";
clrscr();
printf("st = %s",st);
printf("\nstr = %s",str);
getch();
}
gets :
It gets a string from stdin(keyboard).
Syntax :
char * gets(char *s);
Eg :
1) gets(st);
2) gets(welcome); -> not possible
puts :
It outputs a string to stdout (monitor)and appends
a new line character.
Eg :
1) puts(st);
2) puts(welcome); -> possible
Program : str2.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20];
clrscr();
puts("Enter a String : ");
gets(st);
puts("Given String : ");
puts(st);
getch();
}
getch:
It gets a character from the console but doesnot
echo to the screen.
getche :
It gets a character from the console and echoes to
the screen.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
char che;
clrscr();
printf("Enter first character : ");
ch=getch();
printf("Enter second character : ");
che=getche();
printf("First character : %c"ch);
printf("Second character : %c"che);
getch();
}
Note :
putchar :
It is a macro that outputs a character on stdout.
Program : str4.c
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character : ");
ch=getchar();
printf("Given character : ");
putchar(ch);
getch();
}
strlen :
It calculates length of given string.
Syntax :
Program : str5.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int len;
char s[20];
clrscr();
printf("Enter a string : ");
gets(s);
len=strlen(s);
printf("Length of given string : %d",len);
getch();
}
strcpy :
It copies one string to another .
Syntax :
char * strcpy(char *dest, const char *src);
Program : str6.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int len;
char s1[20],s2[20];
clrscr();
printf("Enter a string : ");
gets(s1);
strcpy(s2,s1);
printf("\nGiven string : %s",s1);
printf("\nCopied String : %s",s2);
getch();
}
strrev :
Syntax :
char * strrev(char *s);
Program : str7.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[80];
clrscr();
printf("Enter a string : ");
gets(s);
printf("Given string : %s",s);
strrev(s);
printf("\nReverse string : %s",s);
getch();
}
strcat :
It appends one string to another.
Syntax :
char * strcat(char *dest, const char *src);
Note :
strcat appends a copy of src to the end of dest. The length
of resulting string is :
strlen(dest) + strlen(src)
Program : str8.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[80],s2[80];
clrscr();
printf("Enter first string : ");
gets(s1);
printf("Enter second string : ");
gets(s2);
strcat(s1,s2);
printf("\nConcatenation of 2 strings : %s",s1);
getch();
}
strupr :
It converts lower case(a to z) letters in the given string
to upper case(A to Z).
strlwr :
It converts upper case(A to Z) letters in the given
string to lower case(a to z).
Syntax : char * strlwr(char *s);
Program : str9.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[80];
clrscr();
printf("Enter a string : ");
gets(s);
printf("Given string : %s",s);
strlwr(s);
printf("\nGiven string in lower case: %s",s);
strupr(s);
printf("\nGiven string in upper case: %s",s);
getch();
}
strcmp : It compares 2 string with case sensitivity.
Syntax :
syntax:
int stricmp(const char *s1, const char *s2);
strcmpi :
It is a macro which compares 2 string without case
sensitivity.
Syntax :
int strcmpi(const char * s1, const char * s2);
Return value :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[80],s2[80];
int n;
clrscr();
printf("Enter first string : ");
gets(s1);
printf("Enter second string : ");
gets(s2);
// n=strcmp(s1,s2);
n=stricmp(s1,s2);
// n=strcmpi(s1,s2);
if(n==0)
printf("\n2 strings are equal");
if(n<0)
printf("\nFirst string is less than Second string");
if(n>0)
printf("\nFirst string is greater than Second string");
getch();
}
Program : str11.c
To check weather the given string is Plindrome or Not
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[80],s2[80];
int n;
clrscr();
printf("Enter a string : ");
gets(s1);
strcpy(s2,s1);
strrev(s2);
n=strcmp(s1,s2);
if(n==0)
printf("\nGiven string is a Palindrome");
else
printf("\nGiven string is not a Palindrome");
getch();
}
Program : str12.c
#include<stdio.h>
#include<conio.h>
void main()
{
static int a[256],i;
char st[80];
clrscr();
printf("Enter a String : ");
gets(st);
for(i=0;i<strlen(st);i++)
{
a[st[i]]=a[st[i]]+1;
}
printf("\nCharacter Frequency");
printf("\n----------------------\n");
for(i=0;i<256;i++)
{
if(a[i]!=0)
printf("\n%c %d",i,a[i]);
}
getch();
}
Program : str13.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20],ch;
int i=0;
clrscr();
gotoxy(20,15);
printf("Enter Password : ");
while(1)
{
ch=getch();
if(ch==13)
break;
if(ch==8)
{
if(i>0)
{
printf("\b%c\b",32);
i--;
}
}
else
{
st[i]=ch;
i++;
printf("*");
}
}
st[i]='\0';
gotoxy(20,30);
printf("Given String : %s",st);
getch();
}
Program : str14.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[40];
int i,j,c;
clrscr();
printf("Enter a String : ");
gets(st);
_setcursortype(_NOCURSOR);
while(1)
{
c=(80-strlen(st))/2;
clrscr();
gotoxy(c,1);
printf("%s",st);
for(i=0;i<strlen(st);i++)
{
if(st[i]!=0)
{
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++;
}
}
}
Program : str15.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[40];
int c,i,j;
clrscr();
printf("Enter a string : ");
gets(st);
_setcursortype(_NOCURSOR);
while(!kbhit()) // while(1)
{
c=(80-strlen(st))/2;
clrscr();
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);
}
}
}
}
}
Program : str16.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[40],ch;
int c,i;
clrscr();
printf("Enter a string : ");
gets(st);
strcat(st," ");
strupr(st);
clrscr();
textmode(1);
_setcursortype(_NOCURSOR);
textbackground(WHITE);
textcolor(RED);
c=(40-strlen(st))/2;
gotoxy(c,12);
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(100);
}
getch();
}
Program : strarr1.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20][20];
int n,i;
clrscr();
printf("Enter number of strings : ");
scanf("%d",&n);
printf("Enter %d strings : ",n);
fflush(stdin);
for(i=0;i<n;i++)
{
gets(st[i]);
}
printf("\nGiven strings : ");
for(i=0;i<n;i++)
{
puts(st[i]);
}
getch();
}
Program : strarr2.c
#include<stdio.h>
#include<conio.h>
void main()
{
char st[20][20],t[20];
int n,i,j,k;
clrscr();
printf("Enter number of strings : ");
scanf("%d",&n);
printf("Enter %d strings : \n",n);
fflush(stdin);
for(i=0;i<n;i++)
{
gets(st[i]);
}
printf("\nGiven strings : \n");
for(i=0;i<n;i++)
{
puts(st[i]);
}
// soring //
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
k=strcmp(st[i],st[j]);
if(k>0)
{
strcpy(t,st[i]);
strcpy(st[i],st[j]);
strcpy(st[j],t);
}
}
}
printf("\nGiven strings in Alphabetical order : \n");
for(i=0;i<n;i++)
{
puts(st[i]);
}
getch();
}
#include:
Syntax:
#define :
Syntax:
eg:
#define pf printf
#define sf scanf
Program : sim_mac.c
#include<stdio.h>
#include<conio.h>
#define pf printf
#define sf scanf
#define vm void main()
#define cls clrscr
#define gt getch
#define val 100
vm()
{
int n;
cls();
pf("Enter a number : ");
sf("%d",&n);
pf("Given Number = "%d",n);
p("\nval = %d",val);
gt();
}
Form 2 : (complex macro or macro with arguments)
Syntax:
Eg:
#define square(x) x*x
Program : comx_mac.c
#include<stdio.h>
#include<conio.h>
#define square(x) x*x
void main()
{
int n,s;
clrscr();
printf("Enter a number : ");
scanf("%d",&n);
s=square(n);
printf("Square of given number = %d",s);
getch();
}
Program : macr_def.c
#include<stdio.h>
#include<conio.h>
//#define square(x) x*x
//#define square(x) (x*x)
void main()
{
int n;
n=100/square(5);
printf("n = %d",n);
getch();
}
Program : macr_max.c
#include<stdio.h>
#include<conio.h>
#define maxval(a,b) a>b ? a:b
void main()
{
int a,b,max;
clrscr();
printf("Enter any two values : ");
scanf("%d%d",&a,&b);
max=maxval(a,b);
printf("Maximum value = %d",max);
getch();
}
Note :
Program : comp_dir.c
#include<stdio.h>
#include<conio.h>
#define n 10
#if n<=10
#define val 100
#else
#define val 200
#endif
void main()
{
clrscr();
printf("Val = %d",val);
getch();
}
Pointers
C provides the important feature of data
manipulations with the address of the variables. Hence the
execution time is very much reduced. Such concept is
possible with the special data type called pointers.
Definition :
Declaration :
Initialization :
Example :
int a;
int *p = &a;
datatype *identifier;
identifier=Address;
eg:
int *p;
int a;
p=&a;
void * :
It is a generic pointer, it refers the address of any type of
variable and also it will convert to any type of pointer.
eg:
void *p;
NULL :
Note :
#include<stdio.h>
#include<conio.h>
void main()
{
int *p1;
char *p2;
float *p3;
double *p4;
clrscr();
printf("size of int pointer = %d bytes",sizeof(p1));
printf("\nsize of char pointer = %d bytes",sizeof(p2));
printf("\nsize of float pointer = %d bytes",sizeof(p3));
printf("\nsize of double pointer = %d bytes",sizeof(p4));
getch();
}
Accessing pointers :
a - 100 *p - 100
&a - 5000 p - 5000
a = 200 *p=200
Program : ptr2.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100;
int *p=&n;
clrscr();
printf("value of a = %d",a);
printf("\naddress of a = %lu",&a);
printf("\nvalue of a using p = %d",*p);
printf("\naddress of a using p = %lu",p);
n=200;
printf("\n *p = %d",*p);
*p=300;
printf("\n a = %d",a);
getch();
}
Program : fn1.c
#include<stdio.h>
#include<conio.h>
void main()
{
void fun(int);
clrscr();
fun(100);
getch();
}
void fun(int x)
{
printf("%d",x);
}
Program : fn2.c
Passing a variable
#include<stdio.h>
#include<conio.h>
void main()
{
void fun(int);
int n;
clrscr();
printf("Enter any value : ");
scanf("%d",&n);
fun(n);
getch();
}
void fun(int x)
{
printf("Given value = %d",x);
}
Program : fn3.c
Passing an expression
#include<stdio.h>
#include<conio.h>
void main()
{
void fun(int);
int a,b;
clrscr();
printf("Enter any two numbers : ");
scanf("%d%d",&a,&b);
fun(a+b);
getch();
}
void fun(int x)
{
printf("Sum = %d",x);
}
Call by reference :
Program : ptrfn1.c
#include<stdio.h>
#include<conio.h>
void main()
{
void setdata(int *);
int a;
clrscr();
setdata(&a);
printf("a=%d",a);
getch();
}
void setdata(int *p)
{
*p=100;
}
Program : ptrfn2.c
#include<stdio.h>
#include<conio.h>
void main()
{
void accept(int *);
int n;
clrscr();
accept(&n);
printf("Given value = %d",n);
getch();
}
void accept(int *p)
{
printf("Enter a value : ");
scanf("%d",p);
}
Program : ptrfn3.c
Swaping of 2 values using call by reference
#include<stdio.h>
#include<conio.h>
void main()
{
void swap(int *,int *);
int a,b;
clrscr();
printf("Enter 2 values : ");
scanf("%d%d",&a,&b);
printf("\nGiven values before swaping : ");
printf("\na=%d",a);
printf("\nb=%d",b);
printf("\n\nGiven values after swaping : ");
swap(&a,&b);
printf("\na=%d",a);
printf("\nb=%d",b);
getch();
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Program : ptrarr1.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
clrscr();
printf("Base address : %u",&a[0]);
printf("\nBase address : %u",a);
getch();
}
Note :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,*p;
p=a; //p=&a[0];
clrscr();
printf("Enter number of elements : ");
scanf("%d",&n);
printf("Enter array elements : ");
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
//directly we can give (a+i) without declaring *p, but
it is not efficient
}
printf("\nGiven array elements : ");
for(i=0;i<n;i++)
{
printf("%d\t",*(p+i));
// here also we can give *(a+i), instead of *(p+i)
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char *st;
clrscr();
printf("Enter a String : ");
gets(st);
printf("Given String : %s",st);
getch();
}
We need not specify the size of String, the
compiler
automatically allocates sufficient
amount of memory
Program : ptrstr2.c
#include<stdio.h>
#include<conio.h>
void main()
{
char *st1,*st2;
clrscr();
printf("Enter a String : ");
gets(st1);
st2=st1;
printf("Given String : %s",st1);
printf("\nCopied String : %s",st2);
getch();
}
Dynamic Memory Allocation(DMA) :
Definition :
malloc : <alloc.h>
Syntax :
void * malloc(size_t size);
Eg :
int *p;
calloc : <alloc.h>
Syntax :
void * calloc(size_t nitems , size_t size);
int *p;
p = (int *) calloc(1, sizeof(int)) ; // 1 location
p = (int *) calloc(5, sizeof(int)) ; // 5 locations
free : <alloc.h>
Program : dma1.c
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *p1,*p2,i;
p1=(int *)malloc(5*sizeof(int));
p2=(int *)calloc(5,sizeof(int));
clrscr();
printf("MALLOC : ");
for(i=0;i<5;i++)
{
printf("%d\t",*(p1+i));
}
printf("\nCALLOC : ");
for(i=0;i<5;i++)
{
printf("%d\t",*(p2+i));
}
free(p1);
free(p2);
getch();
}
Program : dma2.c
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *p,n,i;
clrscr();
printf("Enter number of elements : ");
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
//p=(int *)calloc(n,sizeof(int));
printf("Enter elements : ");
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
}
printf("\nGiven elements : ");
for(i=0;i<n;i++)
{
printf("%d\t",*(p+i));
}
free(p);
getch();
}
realloc : <alloc.h>
It reallocates main memory at run time.
Program : realloc1.c
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
void main()
{
char *str;
clrscr();
str=(char *)malloc(10);
strcpy(str,"Hellow");
printf("Given String : %s",str);
str=(char *)realloc(str,25);
strcat(str," Welcome to BDPS");
printf("\nNew String : %s",str);
free(str);
getch();
}
Program : realloc2.c
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *p,id=0,i,s;
char ch;
clrscr();
s=sizeof(int);
p=(int *)malloc(s);
while(1)
{
printf("Enter element : ");
scanf("%d",(p+id));
id++;
printf("Do u want to add another element (y/n) : ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
{
s=s+sizeof(int);
p=(int *)realloc(p,s);
}
else
break;
}
printf("\nGiven elements : ");
for(i=0;i<id;i++)
{
printf("%d\t",*(p+i));
}
free(p);
getch();
}
Structures
We have seen that arrays can be used to represent a
group of data items that belongs to same data type. If we
want to represent a collection of data items of different
data types using a single name, then we cannot use an
array. C supports a constructed data type known as
Structure, which is a method for packing data of different
data types.
A structure is a convenient tool for handling a group
of logically related data items. Structures help to organize
complex data in a more meaningful way. It is a powerful
concept that we may often need to
use in our program design.
Definition :
A group of data items that belongs to different data
types is known as Structure.
Declaration :
Form : 1
Declaration of structure :
struct struct_name
{
data item-1;
data item-2;
data item-n;
};
Eg :
struct emp
{
int eno;
char ename[20];
float sal;
};
Eg:
struct emp e;
(or)
struct emp e1,e2,..,en;
Form : 2
struct struct_name
{
data item-1;
data item-2;
data item-n;
}var_list;
Eg :
struct emp
{
int eno;
char ename[20];
float sal;
}e;
(or)
struct emp
{
int eno;
char ename[20];
float sal;
}e1,e2...,en;
. (Access operator) :
Syntax :
struct_variable . dataitem;
Eg:
e.eno;
e.ename;
e.sal;
Initialization :
Form : 1
struct struct_name
{
data item-1;
data item-2;
data item-n;
};
Eg :
struct emp
{
int eno;
char ename[20];
float sal;
};
struct emp e = {100,HHHH,20000.00};
Form : 2
struct struct_name
{
data item-1;
data item-2;
data item-n;
}identifier = {value-1,value-2,value-n};
Eg :
struct emp
{
int eno;
char ename[20];
float sal;
}e = {100,HHHH,20000.00};
Program : struct1.c
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[20];
float sal;
};
//} e={1,"HHHH",90000.00};
void main()
{
struct emp e={1,"HHHH",90000};
clrscr();
printf("\nEmp number : %d",e.eno);
printf("\nEmp name : %s",e.ename);
printf("\nSalary : %.2f",e.sal);
getch();
}
Program : struct2.c
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[20];
float sal;
};
void main()
{
struct emp e;
clrscr();
printf("Enter emp number : ");
scanf("%d",&e.eno);
printf("Enter emp name : ");
fflush(stdin);
gets(e.ename);
printf("Enter salary : ");
scanf("%f",&e.sal);
printf("\n\nGiven Employ data ");
printf("\n-------------------");
printf("\nEmp number : %d",e.eno);
printf("\nEmp name : %s",e.ename);
printf("\nSalary : %.2f",e.sal);
getch();
}
Program : struct3.c
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
int sno,c,cpp,java,tot;
float avg;
char sname[20],res[10],div[12];
}s;
void main()
{
clrscr();
printf("Enter Student number : ");
scanf("%d",&s.sno);
printf("Enter Student name : ");
fflush(stdin);
gets(s.sname);
printf("Enter marks in C : ");
scanf("%d",&s.c);
printf("Enter marks in CPP : ");
scanf("%d",&s.cpp);
printf("Enter marks in JAVA : ");
scanf("%d",&s.java);
s.tot=s.c+s.cpp+s.java;
s.avg=(float)s.tot/3;
if(s.c>=50 && s.cpp>=50 && s.java>=50)
{
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("Student Details");
printf("\n-------------------------");
printf("\nStudent number : %d",s.sno);
printf("\nStudent name : %s",s.sname);
printf("\nMarks in C : %d",s.c);
printf("\nMarks in CPP : %d",s.cpp);
printf("\nMarks in JAVA : %d",s.java);
printf("\nTotal Marks : %d",s.tot);
printf("\nAverage Marks : %.2f",s.avg);
printf("\nResult : %s",s.res);
printf("\nDivision : %s",s.div);
getch();
}
Array of Structures :
Program : struct_ar1.c
#include<stdio.h>
#include<conio.h>
struct item
{
int code;
char name[20];
float cost;
};
void main()
{
struct item it[100];
int n,i;
float *f,f1;
clrscr();
f=&f1;
*f=f1;
printf("Enter numer of records : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter Record : %d",i+1);
printf("\n\nEnter Item code : ");
scanf("%d",&it[i].code);
printf("Enter Item Name : ");
fflush(stdin);
gets(it[i].name);
printf("Enter Item cost : ");
scanf("%f",&it[i].cost);
}
clrscr();
printf("%-10s%-15s%s","CODE","NAME","COST");
printf("\n------------------------------");
for(i=0;i<n;i++)
{
printf("\n%-10d%-15s
%.2f",it[i].code,it[i].name,it[i].cost);
}
getch();
}
The allocation of variables in heap contains 2 parts. One
is for integral data types (int and char), and the other is for
float type.
Program : struct_ar2.c
Returning structure :
Program : s_pasret.c
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20],course[20];
float fee;
};
For example :
struct student
{
int sno;
char sname[20], course[20];
float fee;
};
struct student s;
struct student *p;
(Arrow)
--------------
-> is the combination of - followed by > .
syntax:
Struct_pointer -> data item;
Eg:
p sno;
p sname;
p course;
p fee;
Pro
gram : stru_ptr.c
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20],course[20];
float fee;
};
void main()
{
struct student s;
struct student *p;
float *f,f1;
f=&f1;
*f=f1;
p=&s;
clrscr();
/* Indirect method
printf("Enter Student Number : ");
scanf("%d",&(*p).sno);
printf("Enter Student Name : ");
fflush(stdin);
gets((*p).sname);
printf("Enter Course : ");
gets((*p).course);
printf("Enter Fee : ");
scanf("%f",&(*p).fee);
printf("\n\nSTUDENT DETAILS");
printf("\n-------------------\n");
printf("\nStudent Number : %d",(*p).sno);
printf("\nStudent Name : %s",(*p).sname);
printf("\nCourse : %s",(*p).course);
printf("\nFees : %.2f",(*p).fee); */
/* Direct method
printf("Enter Student Number : ");
scanf("%d",&p->sno);
printf("Enter Student Name : ");
fflush(stdin);
gets(p->sname);
printf("Enter Course : ");
gets(p->course);
printf("Enter Fee : ");
scanf("%f",&p->fee);
printf("\n\nSTUDENT DETAILS");
printf("\n-------------------\n");
printf("\nStudent Number : %d",p->sno);
printf("\nStudent Name : %s",p->sname);
printf("\nCourse : %s",p->course);
printf("\nFees : %.2f",p->fee); */
getch();
}
1. date :
Syntax :
struct date
{
int da_year; // current year
char da_day; // day of month
char da_mon; // month (Jan=1)
};
getdate :
Program : sysdate.c
2. time :
It is a pre-defined structure and used to get current
system time. It is included in the header file <DOS.H>
Syntax :
struct time
{
unsigned char ti_min; // minutes
unsigned char ti_hour; // hours
unsigned char ti_sec; // seconds
};
gettime :
Program : systime.c
struct ffblk :
Syntax :
struct ffblk
{
char ff_reserved[21]; //reserved by DOS
char ff_attrib; //attribute found
char ff_ftime; //file time
char ff_fdate; //file date
char ff_fsize; //file size
char ff_name; //found file name
};
findfirst() :
List of attributes :
These attributes are included in the header file <dos.h>
CONSTANT
DESCRIPTION
Return Value :
Program : ffblk.c
#include<stdio.h>
#include<conio.h>
#include<dir.h>
#include<dos.h>
void main()
{
struct ffblk f;
int d,count=0;
char st[50];
clrscr();
printf("Enter Path : ");
gets(st);
d=findfirst(st,&f,FA_ARCH);
while(!d)
{
printf("\n%s",f.ff_name);
count++;
if(count%20==0)
{
printf("\n\nPress any key to Continue......");
getch();
clrscr();
}
d=findnext(&f);
}
printf("\n\tTotal number of Files : %d",count);
getch();
}
Output
1) Enter path :
*.*
It will display all file in the current working directory.
2) Enter path :
*.c
It will display all .C programs in the current working
directory.
Bit fields :
C permits us to use small bit fields to hold data. We
have been using integer field of size 16 bit to store data.
The data item requires much less than 16 bits of space, in
such case we waste memory space. In this situation we
use small bit fields in structures.
Note :
Syntax :
struct struct_name
{
unsigned (or) int identifier1 : bit_length;
unsigned (or) int identifier2 : bit_length;
.
.
unsigned (or) int identifierN : bit_length;
};
Program : bit_stru.c
#include<stdio.h>
#include<conio.h>
struct emp
{
unsigned eno:7;
char ename[20];
unsigned age:6;
float sal;
unsigned ms:1;
};
void main()
{
struct emp e;
int n;
clrscr();
printf("Enter eno : ");
scanf("%d",&n);
e.eno=n;
printf("Enter ename : ");
fflush(stdin);
gets(e.ename);
printf("Enter age : ");
scanf("%d",&n);
e.age=n;
printf("Enter salary : ");
scanf("%f",&e.sal);
printf("Enter Marital Status : ");
scanf("%d",&n);
e.ms=n;
clrscr();
printf("Employ number : %d",e.eno);
printf("\nEmploy name : %s",e.ename);
printf("\nEmploy age : %d",e.age);
printf("\nEmploy salary : %.2f",e.sal);
printf("\nMarital status : %d",e.ms);
getch();
}
Union:
union union_name
{
data item1;
data item2;
data item-n;
} [var_list];
Eg :
union test
{
int n;
char ch;
float ft;
} t;
Program : un_stru.c
#include<stdio.h>
#include<conio.h>
struct test1
{
int n;
char c;
float f;
}t1;
union test2
{
int n;
char c;
float f;
}t2;
void main()
{
clrscr();
printf("Memory size of struct : %d bytes",sizeof(t1));
printf("\nMemory size of union : %d bytes",sizeof(t2));
getch();
}
Output
STRUCT UNION
Program : union.c
#include<stdio.h>
#include<conio.h>
union emp
{
int eno;
char ename[20];
float sal;
};
void main()
{
union emp e;
printf("Enter empno : ");
scanf("%d",&e.eno);
printf("Emp number : %d",e.eno);
printf("\n\nEnter empname : ");
fflush(stdin);
gets(e.ename);
printf("Emp name : %s",e.ename);
printf("\n\nEnter empsal : ");
scanf("%f",&e.sal);
printf("Salary : %.2f",e.sal);
}
<dir.h> functions :
1. getcwd :
Program : getcwd.c
#include<stdio.h>
#include<conio.h>
#include<dir.h>
void main()
{
char st[80];
clrscr();
getcwd(st,80);
printf("Current Working Directory : %s",st);
getch();
}
2. chdir :
Return Value :
Program : chdir.c
#include<stdio.h>
#include<conio.h>
#include<dir.h>
void main()
{
char st[80];
int n;
clrscr();
printf("Enter path : ");
gets(st);
n=chdir(st);
if(n==0)
printf("Directory Changed");
else
printf("Directory not Changed");
getch();
}
Output
Enter path :
E:\raji\cpp\programs
We will get the message Directory Changed
To check whether we have changed to that specific
directory or not, run the getcwd.c program in that
directory, then it will display the current working
directory as : E:\raji\cpp\programs.
3. mkdir :
It creates a directory
Syntax : int mkdir(const char *path);
Return Value :
Program : mkdir.c
#include<stdio.h>
#include<conio.h>
#include<dir.h>
void main()
{
char st[80];
int n;
clrscr();
printf("Enter Path : ");
gets(st);
n=mkdir(st);
if(n==0)
printf("Directory Created");
else
printf("Unable to Create a Directory");
}
Output
Enter path :
rr
Directory is created in our current directory.
If we gives the same path once again, we will get
Unable to create a dir
Go to command prompt and type dir, then directory rr is
displayed at the last
4. rmdir :
Return Value :
Program : rmdir.c
#include<stdio.h>
#include<conio.h>
#include<dir.h>
void main()
{
char st[50];
int n;
clrscr();
printf("Enter Path : ");
gets(st);
n=rmdir(st);
if(n==0)
printf("Directory is deleted");
else
printf("Unable to delete a Directory");
getch();
}
Output
E:\raji\c\programs> type aa
Then the above data is displayed
E:\raji\c\programs> cd ram
Directory created
Now our current working directory has 2 sub directories,
called raji and ram.
We can delete the sub directory ram by using rmdir(), but
we cannot deleted the directory raji, because raji contain
one text file aa.txt, but ram is empty, hence we can
remove it.
Now we can delete the folder raji with the help of rmdir().
Files
C language permits the usage of limited input and
output functions to read and write data. These functions
are used for only smaller volume of data and it becomes
difficult to handle longer data volumes. Also the entire
data is lost when the program over.
To overcome these difficulties a flexible method was
developed by employing the concept of files to store, to
read and write data and to return them even when the
program over.
Definition :
Types of files :
Files are two types, Namely
1. Text files (or)
Sequential files
2. Binary files
Text files :
Used for reading and writing data in the form of
characters. The memory size of each and every character
is 1 byte.
Binary files :
FILE :
Syntax :
FILE *identifier.
Eg:
FILE *fp;
File handling functions :
Syntax :
mode string :
There are various modes and are described in the
following table.
String Description
.
r Open for reading only.
1 To specify that a
given file is being opened or created in text mode, append "t" to
the string (rt, w+t, etc.).
2 To specify
binary mode, append "b" to the string (wb, a+b, etc.).
fclose :
It closes a file .
Syntax :
int fclose(FILE *fp);
Syntax :
int fcloseall();
Program : file1.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("a.txt","w");
if(fp==NULL)
printf("Unable to open a file");
else
printf("File is opened");
getch();
}
Textfiles
Syntax :
int getc(FILE *stream);
Syntax :
Syntax :
int fgetc(FILE *stream);
Syntax :
int fputc(int c,FILE *stream);
EOF :
It is a constant indicating that end of file has been
reached on a File. To get this character from keyboard
press Ctrl+Z (or) F6
Program : file2.c
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp;
clrscr();
fp=fopen("a.txt","wt");
printf("Enter data (Ctrl+Z to stop) : ");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
printf("Data stored successfully");
getch();
}
Program : file3.c
To open a file and to read data from the file and display
on the monitor
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("a.txt","rt");
printf("Reading data from the file\n\n");
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
getch();
}
Program : file4.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch,st[20];
clrscr();
printf("Enter File name : ");
gets(st);
fp=fopen(st,"rt");
if(fp==NULL)
{
printf("\nFile not found");
getch();
exit(0);
}
printf("\n\nReading data from the file\n\n");
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
delay(10);
}
fclose(fp);
getch();
}
Program : file5.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch,ch1,st[20];
int nc=0,nw=0,nl=0;
clrscr();
printf("Enter File name : ");
gets(st);
fp=fopen(st,"rt");
if(fp==NULL)
{
printf("\nFile not found");
getch();
exit(0);
}
ch=getc(fp);
while(ch!=EOF)
{
if(ch==32 || ch=='\n')
{
nw++;
if(ch=='\n')
nl++;
}
else
nc++;
ch1=ch;
ch=getc(fp);
if(ch==32 && ch1==ch)
nw--;
}
printf("\n Number of characters : %d",nc);
printf("\n Number of words : %d",nw);
printf("\n Number of lines : %d",nl);
fclose(fp);
getch();
}
rewind() :
Program : file6.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("a.txt","a+t");
printf("Enter data (Ctrl+Z to stop) : ");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
printf("\nData stored successfully");
rewind(fp);
printf("\n\nReading data from the file\n\n");
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
getch();
}
fgets :
fputs :
feof :
Return value :
1 Returns non
zero if an end of file indicator was detected on the
last input operation on the named stream.
2 Returns 0 if
end of file has not been reached.
Program : file7.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char st[80];
clrscr();
fp=fopen("str.txt","a+t");
printf("Enter string data ('end' to stop) : ");
gets(st);
while(strcmp(st,"end")!=0)
{
fputs(st,fp);
fputs("\n",fp);
gets(st);
}
rewind(fp);
printf("\nReading data from the file :\n");
fgets(st,80,fp);
while(!feof(fp))
{
printf("%s",st);
fgets(st,80,fp);
}
getch();
fclose(fp);
}
Output
Enter data :
Raji
Ram
Ramraji
Rajiram
Bunny
end
fprintf:
Syntax :
fscanf :
Syntax :
int fscanf(FILE *stream,const char *format [,address,...]);
Note :
Program : file8.c
#include<stdio.h>
#include<conio.h>
void main()
{
int eno;
char ename[20];
float sal;
FILE *fp;
clrscr();
fp=fopen("emp.txt","wt");
printf("Enter empno : ");
scanf("%d",&eno);
printf("Enter ename : ");
fflush(stdin);
gets(ename);
printf("Enter sal : ");
scanf("%f",&sal);
fprintf(fp,"%d %s %.2f",eno,ename,sal);
fclose(fp);
printf("\nRecord saved successfully");
getch();
}
Program : file9.c
#include<stdio.h>
#include<conio.h>
void main()
{
int eno;
char ename[20];
float sal;
FILE *fp;
clrscr();
fp=fopen("emp.txt","rt");
fscanf(fp,"%d %s %f",&eno,ename,&sal);
fclose(fp);
printf("\nReading data from file");
printf("\n\nEnter empno : %d",eno);
printf("\nEnter ename : %s",ename);
printf("\nEnter sal : %.2f",sal);
getch();
}
Program : file10.c
#include<stdio.h>
#include<conio.h>
void main()
{
int eno;
char ename[20],ch;
float sal;
FILE *fp;
clrscr();
fp=fopen("emp1.txt","a+t");
do
{
printf("Enter empno : ");
scanf("%d",&eno);
printf("Enter ename : ");
fflush(stdin);
gets(ename);
printf("Enter sal : ");
scanf("%f",&sal);
fprintf(fp,"%d %s %.2f \n",eno,ename,sal);
printf("\n\nRecord saved successfully");
printf("\n\nDo u want to add another record (y/n) : ");
fflush(stdin);
scanf("%c",&ch);
} while(ch!='n');
rewind(fp);
printf("\nReading data from file\n\n");
printf("%-10s%-15s%s","ENO","ENAME","SAL");
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 :
fseek :
Syntax :
offset :
Difference in bytes between whence and new position.
whence :
One of three SEEK_xxx file pointer locations (0, 1, or 2)
Program : file11.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("z.txt","w");
printf("Current file pointer position : %lu",ftell(fp));
printf("\n\nEnter data (Ctrl+Z to stop): ");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
printf("Present file pointer position : %lu",ftell(fp));
fseek(fp,-10,1); // fseek(fp,-10,SEEK_CUR);
printf("\nNew file pointer position : %lu",ftell(fp));
fclose(fp);
getch();
}
getw :
Syntax :
int getw(FILE *stream);
putw:
Syntax :
int putw(int w, FILE *stream);
Program : file12.c
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen("a.dat","a+b"); // append in binary format
printf("Enter data (0 to stop) : \n\n");
scanf("%d",&n);
while(n!=0)
{
putw(n,fp);
scanf("%d",&n);
}
fseek(fp,0,0); //rewind(fp);
printf("\n\nReading data from file : \n\n");
n=getw(fp);
while(!feof(fp))
{
printf("%d\n",n);
n=getw(fp);
}
fclose(fp);
getch();
}
fwrite :
Syntax :
fread :
It reads specified number of equal sized data blocks from an input file.
Syntax :
argumnet description
ptr pointer to a block which data
is read/write
Program : file13.c
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20],course[10];
float fee;
};
void main()
{
struct student s;
FILE *fp;
clrscr();
fp=fopen("student.dat","wb");
printf("Enter student number : ");
scanf("%d",&s.sno);
printf("Enter student name : ");
fflush(stdin);
gets(s.sname);
printf("Enter course : ");
gets(s.course);
printf("Enter fee : ");
scanf("%f",&s.fee);
fwrite(&s,sizeof(s),1,fp);
fclose(fp);
printf("\n\nRecord save sucessfully");
getch();
}
Program : file14.c
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20],course[10];
float fee;
};
void main()
{
struct student s;
FILE *fp;
clrscr();
fp=fopen("student.dat","rb");
fread(&s,sizeof(s),1,fp);
printf("Reading data from file\n\n");
printf("Student number : %d",s.sno);
printf("\nStudent name : %s",s.sname);
printf("\nCourse : %s",s.course);
printf("\nFee : %.2f",s.fee);
fclose(fp);
getch();
}
Program : file15.c
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[20],course[5];
float fee;
};
void main()
{
FILE *fp;
char ch;
struct student s;
clrscr();
fp=fopen("student.dat","a+b");
do
{
printf("Enter student number : ");
scanf("%d",&s.sno);
printf("Enter student name : ");
fflush(stdin);
gets(s.sname);
printf("Enter course : ");
fflush(stdin);
gets(s.course);
printf("Enter fee : ");
scanf("%f",&s.fee);
fwrite(&s,sizeof(s),1,fp);
printf("\nRecord saved successfully");
printf("\n\nDo you want to add another record (y/n) : ");
fflush(stdin);
scanf("%c",&ch);
}
while(ch!='n');
fseek(fp,0,0);
fread(&s,sizeof(s),1,fp);
while(!feof(fp))
{
clrscr();
printf("\nStudent number : %d",s.sno);
printf("\nStudent name : %s",s.sname);
printf("\ncourse : %s",s.course);
printf("\nFee : %.2f",s.fee);
printf("\n\nPress any kee to contune.........");
getch();
fread(&s,sizeof(s),1,fp);
}
fclose(fp);
getch();
}
enum,typedef
Program : cla1.c
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
int i;
clrscr();
printf("Number of argument : %d",argc);
for(i=0;i<argc;i++)
{
printf("\nargument[%d] : %s",i,argv[i]);
}
getch();
}
Program : cla2.c
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
FILE *fp;
char ch;
clrscr();
if(argc!=2)
{
printf("Invalid arguments");
exit(0);
}
fp=fopen(argv[1],"w");
ch=getchar();
while(ch!=EOF)
{
putc(ch,fp);
ch=getchar();
}
fclose(fp);
printf("File created");
getch();
}
Program : cla3.c
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
FILE *fp;
char ch;
clrscr();
if(argc!=2)
{
printf("Invalid arguments");
exit(0);
}
fp=fopen(argv[1],"r");
if(fp==NULL)
{
printf("File not found");
exit(0);
}
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
getch();
}
Program : cla4.c
#include<stdio.h>
#include<conio.h>
void main(int argc,char *argv[])
{
FILE *fp1,*fp2;
char ch;
if(argc!=3)
{
printf("Invalid arguments");
exit(0);
}
fp1=fopen(argv[1],"r");
if(fp1==NULL)
{
printf("File not found");
exit(0);
}
fp2=fopen(argv[2],"r");
if(fp2!=NULL)
{
printf("File already exists : %s",argv[2]);
printf("\nDo you want to override (y/n) : ");
scanf("%c",&ch);
if(ch=='n'||ch=='N')
{
printf("Unable to copy a file");
fcloseall();
exit(0);
}
fclose(fp2);
fp2=fopen(argv[2],"w");
ch=getc(fp1);
while(ch!=EOF)
{
putc(ch,fp2);
ch=getc(fp1);
}
fcloseall();
}
printf("File copied successfully");
}
Program : design.h
#include<stdio.h>
#include<conio.h>
void hline(int r,int sc,int ec)
{
int i;
for(i=sc;i<=ec;i++)
{
gotoxy(i,r);
printf("%c",196);
}
}
void vline(int c,int sr,int er)
{
int i;
for(i=sr;i<=er;i++)
{
gotoxy(c,i);
printf("%c",179);
}
}
void box(int sc,int sr,int ec,int er)
{
gotoxy(sc,sr);
printf("%c",218);
gotoxy(ec,sr);
printf("%c",191);
gotoxy(sc,er);
printf("%c",192);
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 : shuffle.c
#include<process.h>
#include<stdlib.h>
#include"design.h"
void main()
{
void generate(int [][4]);
int a[4][4];
int i,j,r,c,count=0;
char ch;
_setcursortype(_NOCURSOR);
generate(a);
while(1)
{
clrscr();
gotoxy(35,2);
printf("SHUFFLE GAME");
box(22,3,58,19);
hline(7,23,57);
hline(11,23,57);
hline(15,23,57);
vline(30,4,18);
vline(40,4,18);
vline(50,4,18);
gotoxy(32,21);
printf("Number of key strokes : %d",count);
gotoxy(35,23);
printf("Esc to exit");
gotoxy(35,25);
printf("Alt+S to shuffle");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
gotoxy(25+j*10,5+i*4);
if(a[i][j]!=0)
printf("%d",a[i][j]);
else
{
r=i;
c=j;
}
}
}
ch=getch();
if(ch==0)
ch=getch();
count++;
if(count>200)
{
clrscr();
textcolor(15+128);
gotoxy(35,12);
printf("GAME OVER");
getch();
exit(0);
}
switch(ch)
{
case 80:
if(r>0)
{
a[r][c]=a[r-1][c];
a[r-1][c]=0;
}
break;
case 72:
if(r<3)
{
a[r][c]=a[r+1][c];
a[r+1][c]=0;
}
break;
case 77:
if(c>0)
{
a[r][c]=a[r][c-1];
a[r][c-1]=0;
}
break;
case 75:
if(r<3)
{
a[r][c]=a[r][c+1];
a[r][c+1]=0;
}
break;
case 31:
generate(a);
count=0;
break;
case 27:
exit(0);
}
if(a[0][0]==1 && a[0][1]==2 && a[0][2]==3 && a[0]
[3]==4 &&
a[1][0]==5 && a[1][1]==6 && a[1][2]==7 && a[1]
[3]==8 &&
a[2][0]==9 && a[2][1]==10 && a[2][2]==11 &&
a[2][3]==12 &&
a[3][0]==13 && a[3][1]==14 && a[3][2]==15 &&
a[3][3]==0)
{
clrscr();
textcolor(15+128);
gotoxy(35,12);
cprintf("GAME SUCCESS");
gotoxy(32,15);
printf("Number of key strokes : %d",count);
getch();
exit(0);
}
}
}
void generate(int a[][4])
{
int x[16],n,id=0,i,j;
char ck;
randomize();
while(id<16)
{
n=random(16);
ck=0;
for(i=0;i<id;i++)
{
if(x[i]==n)
{
ck=1;
break;
}
}
if(ck==0)
{
x[id]=n;
id++;
}
}
id=0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
a[i][j]=x[id];
id++;
}
}
}
Conversion functions: