Sie sind auf Seite 1von 98

QUALITY COMPUTER EDUCATION

Language
The media of communication between the user and the system is known as Language. It
is classified into three types. They are.

a) Machine language: This language is also known as binary language or first


generation language or low level language. It consists of binary digits or bits
(0-pulse off,1-pulse on).

b) Assembly language: It is also known as middle level language or second


generation language. Its process is faster than high level language and easy to
understand when compared to machine language.
Ex: c, c++

c) High level language: This is the user language. It consists of codes which is
very easy to understand as the code is similar to English language.
Ex: BASIC, COBOL, FORTRAN, JAVA, C#

Operating system: It is an interface between user and the computer. It is used to


perform the required operations in the system. It is classified into two types. They are

1) single user operating system: it supports only one user at a time. These are
micro computers
Ex: DOS
2) Multi user operating system: it supports more than one user at a time. These
are mini, main-frame and super computers.
Ex: Windows NT, UNIX, XENIX etc.,

Booting: The process of loading an operating system into the computer internal memory
is known as Booting. It is classified into two types. They are

1) Cold booting: when the power is switched on then the process of loading
operating system into the computer memory is known as cold booting

2) warm booting: when there is a problem with the computer then the process of
rebooting is known as warm booting. Warm booting is done using warm keys
or control keys (alt+del+ctrl) or Reset button in CPU.

History of c-language:
COBOL :COmmon Business Oriented Language : Business
BASIC : Beginners All purpose Symbolic Instruction Code : Beginners
FORTRAN: FORmula TRANslation : Scientific and Engineering purpose
Dbase : Data base -do-
ALGOL: AlGOrithmic Language : Some requirements.
CPL : Combined Programming Language : More requirement, difficult.
BCPL : Basic Combined Programming Language: More requirement, easy
B : New concepts (different from BCPL).

1
QUALITY COMPUTER EDUCATION

C : BCPL + B + some more features( data types)

Advantages or features of c-language

1) C-language is designed in assembly language because its compilation will be faster


and also easy to understand
2) C-language is used for scientific purpose, engineering purpose, business purpose and
general purpose.
3) C-language is used to design and application software and system software.
Ex: Unix
4) C-language supports the storage classes such as static, external, register and
automatic
5) In C-language a large program is divided into number of functions so that the size of
the program can be reduced as well as program becomes simple.
6) C-language is very easy to understand and use.
7) C-language supports pre-defined functions, user-defined functions and recursive
functions.
8) It is flexible. The same program can be designed in required format with different
logics.
9) Data structures can be build in c-language.
10) Memory can be allocated at run-time using Dynamic Memory Locations.
11) The user can create Derived data types and User-defined data type using the Primary
data types.
12) The arguments can be passed from the command prompt using command line
arguments and can perform required operations.

C-language: It is a middle level language and is known as structured programming


language or function oriented programming language. It is designed and developed by
Dennis Ritchie at AT & T (American Telegraph and Telephone) bell laboratory in USA in
the year 1972. It could satisfy all the user requirements.

Hardware: The set of physical components of the computer is known as hardware

Software : The set of programs (language, package, operating system, files, folders etc)
is known as software.

Firmware: The set of standard routine tasks is known as Firmware

Lineware: The Computer Personnel is known as Lineware

Program: The set of instruction is known as program

Instruction: The set of commands to perform a particular task is known as instruction.

A=5 instruction
B=6 program

2
QUALITY COMPUTER EDUCATION

C=A+B
DISPLAY C

Source code: The code, which is written by the user is known as source code

Object code : The system understandable code is called object code. The source code is
converted into ASCII code or EBCDIC code for the system identification based
on the operating system.

ASCII : American Standard Coded for Information Interchange. It uses 8 bits to


represent a character. It belongs to Microsoft
user ASCII
Ex: A=65, a=97, 0 =48 ,

BCD: Binary coded decimal. It uses 6 bits to represent a character


(IBM=International Business Machine)

EBCDIC: Extended Binary Coded Decimal Interchange Code. It uses 8 bits to


represent a character.

Compiler and interpreter: These are used to convert source code into object code.
Compiler converts the entire program at a time where as interpreter converts the
program in line wise.

0,1 = 1bit
8 bits = 1 byte
1024 bytes = 1 KB ( Kilo Byte)
1024 KB = 1MB (Mega Byte)
1024 MB = 1GB (Giga Bytes)
1024 GB = 1TB (Tera Byte)

Variable: The value, which changes during the execution of a program, is known as
variable. It is used to store the contents in a memory cell.
a

65536 6

a : variable
65536 : address of cell
6 : value in the cell

Rules for writing a variable name

3
QUALITY COMPUTER EDUCATION

1) Every variable name should be started with an alphabet.


2) The length of the variable should not exceed more than 8 characters. Some
compilers may support upto 40 characters.
3) Spaces should not be provided in a variable name.
4) Reserved words should not be used as a variable name.
5) Except underscore, other symbols should not be used as a variable name.
6) A variable can store the value of particular data type only.
Ex: s_no, s1, snumber, a

Constants: The value, which does not change during the execution of the program is
known as constant.

Numericals: the numbers should not contain quotations. These values could be
used for calculations.
Ex: 56, 77.788
Characters: The single character should be enclosed within single quotation. A
character may be numbers, special symbols, space, alphabets
Ex: ‘7’, ‘A’, ‘u’, ‘$’,’ ‘

Strings: the set of characters is known as a string and should be enclosed within
double quotation.
Ex: “ravi”, “123”, ”it is c-language”

Datatypes
it is used to define the type of the data used for a variable so that the contents can be
stored in a variable based on the data type.

1) Primary data types: it is also known as fundamental data types or basic data types.
These data types are generally of 4 types.

a) integer: it is used to accept numeric values, which are used for calculations.It
occupies 2 bytes and it is represented with "int". It is again classified into 3 types.They
are int, short int, long int.

b) Float: it is used to accept numeric values as well as decimal values. it occupies


4 bytes.it is classified into 3 types. Thay are float, double, long double.

c) Character: It is used to accept a single character into a variable. It occupies 1


byte. It is represented with "char".
The collection of characters is referred as string and it is defined
with arrays
ex: char s[4]="ravi"

d) Void: it occupies 0 bytes and it will not return any value.


Type formatted Length Range

4
QUALITY COMPUTER EDUCATION

string
char %c 1 byte -128 to 127
unsigned char %c 1 byte 0 to 255
enum -- 2 bytes -32,768 to 32,767
short int %hd 1 bytes -128 to +127
int %d 2 bytes -32,768 to +32,767
long int %ld 4 bytes -2,147,483,648 to 2,147,483,647
unsigned short int %hu 2 bytes 0 to 255
unsigned int %u 2 bytes 0 to 65,535
unsigned long int %lu 4 bytes 0 to 4,294,967,295
float %f 4 bytes 3.4 * e-38 to 3.4 * e+38
double %lf 8 bytes 1.7 * e- 308 to 1.7 *e+308
long double %Lf 10 bytes 3.4*e-4932 to 1.1*e+4932

2) User-defined data types: By using the all the primary data types, user-defined data
types will be created, i.e., using more than one primary data types a new data type is
created.
ex: struct, class, enum (enumerated data types)
struct student
{
int sno, c, cpp, java;
char sname[500; float avg, total;
}stud;

3) Derived data types: By using a single primary data type a new data type is created, it
is known as Derived data types.
ex: arrays, functions, pointers

clrscr(): This statement is used to clear the screen at run-time.

Rules for writing C Program

1) The header files should be declared at the starting of the program in each line.
ex: # include "stdio.h" (input and output streams)
#include <stdio.h>
If header file is included within quotations then the file will be searched or path
of the file can be specified which may be located in any directory but if the header file is
included within <> then the file will be searched only in the include directory.
2) Every program should contain "main" statement with return-type void. By default it
takes "int" as the return-type. It is the main function where the compiler starts executing
the program.
3) The block of statements should be enclosed within '{' and '}'
4) Every statement should be terminated with semicolon (;)
5) The variable should be declared at the starting of the statement.
6) C is a case sensitive so the program should be written in lower case letters except some

5
QUALITY COMPUTER EDUCATION

keywords, class name etc.,

Shortcuts

f2- save the program file


alt + f9 : Compile the program
ctrl+f9: Run the program
alt +f5 : To display the result
alt + f : File menu
alt + red character in menu bar : to display the options of the corresponding menu.
alt + x : Exit for c++ editor (turbo editor)

Formatted input and output statement

1) scanf(): it is used to accept the contents into the variable until it founds enter
(return) key or space symbol.
Syntax: scanf(“formatted string”,&var1,&var2….);
Example: scanf(“%d”,&a);
scanf(“%d%d%d”,&a,&b,&c);
scanf(“%c”,&ch);

2) printf(): it is used to display the string or to display the contents in the output
screen
Syntax: printf(“string /formatted string”,var1,var2..);
Example: printf(“it is c-language”);
printf(“the value is: %d”,a);

Escape characters

\n - new line
\t - tab space
\a - alert ( bell)
\f - form feed
\b - backspace
\\ - slash symbol
\’ - single quote symbol
\” - double quotation
\r - carriage return
‘\0’ - NULL character

Operators
c-language is rich in operators because it support many number of operators. If true it
returns is 1 otherwise value is 0 for any operator.
ex: c=a+b+10
=, +  operator c,a,b,10 operands (variables, constants)

6
QUALITY COMPUTER EDUCATION

1) Assignment operator: it is used to assign or store a value into the variable.


The operator is =
Syntax: variable=expression;
Ex: c=6 (c  6)
c=(a+b)-(d+e)/f

2) Arithmetic operator: it is used to perform the arithmetical operations. These


operators are also known as basic operators. The operators are +, -, *, \,
%(modulus).
Ex: c=5+7 (c=12)
C=5%2 c=1 (remainder)

3) Relational operators or Comparison operators: These operators are used to


provide relation between the variables. The operators are >,<, >= ,<= , = =

4) Logical operators: These operators are used to provide more than one
condition, as the relational operators can provide only one condition. The
operators are && (and) , || (or), ! (not)

(&&)
Condition1 Condition2 Result
True True True
True False False
False True False
False False False
(||)
Condition1 Condition2 Result
True True True
True False True
False True True
False False False
(!)
Condition1 Result
True False
False True

5) Bitwise operators: These operators are used to perform the arithmetical


operations in terms of bits or binary digits. It is classified into 6 types.

6) Ternary operators: This opertor is also known as conditional operator. It is


used to specify the condition using ? and : operator. These operators are
combinely known as Ternary operator.
Ex: max=(a>b)?a:b;

7
QUALITY COMPUTER EDUCATION

7) Casting Operators: It is used to change the data type of the variable and the
content is stored in the other variable.
Ex: k=(int)f; (where k is int and f is float)
K=(char) ch; (where ch is a character containing
integer
value)

8) Comma Operator: It is used to separate the contents or variable. It is


indicated with ,
Ex: int a,b,c;

9) Unary operators:

a) Address operator: it is represented with &. It is used to specify the address


of a variable.

b) Increment operator: it is indicated with ++. It is used to increase the value of


the variable. It is classified into two types. They are
Pre increment: it is used to increase the value of the variable of the
variable in the present statement. Here the operator is preceded by the
variable
Post increment: it is used to increase the value of the variable of the
variable in the next statement. Here the variable is preceded by the operator.

c) Decrement operator: it is indicated with - -. It is used to decrease the value


of the variable. It is classified into two types. They are
Pre decrement: it is used to decrease the value of the variable of the
variable in the present statement. Here the operator is preceded by the
variable
Post decrement: it is used to decrease the value of the variable of the
variable in the next statement. Here the variable is preceded by the operator.

d) Pointer operator: it is indicated with * . It is used to specify the value in a


pointer variable.
Ex: int *p;

e) typedef operator : it is used to specify the alternative name for a data type so
that this altenative name can be used instead of original data type name
Ex: typedef int integer ;
Integer a,b,c ;

f) sizeof operator : It is used to specify the number of bytes occupied by a


variable.
Ex: printf(« the number of byte of integer var
is :%d »,sizeof(int)) ;

8
QUALITY COMPUTER EDUCATION

10) Other operators: in addition to these operators c++ supports many number of
operators which are used for the special purpose such as - >, .( ) , [] , ,, { } etc.,
Program to display information on the output screen
#include<stdio.h>
void main()
{
clrscr();
printf("welcome to c world");
}

WAP to display your address


#include <stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Name : GRK");
printf("\n D.No. : 19-168");
printf("\n Street : GPT");
printf("\n City : VSP");
getch();
}

Program for demo on “\n” (new line)


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\nhello");
printf("\nhai");
printf("\nthis is ravi");
getch();
}

Program for demo on “\t” (tab space)


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\nWelcome \t to \t c-language");
}

Program to find sum of two numbers


#include<stdio.h>

9
QUALITY COMPUTER EDUCATION

#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter two numbers");
scanf("%d%d",&a,&b);
c=a+b;
printf("sum of two nos:%d",c);
getch();
}

WAP to accept address and display the address


#include <stdio.h>
#include<conio.h>
main()
{
char name[20],st[20],city[20],dno[20];
clrscr();
printf(" Enter Name :");
scanf("%s",name);
printf(" Enter D.No. :");
scanf("%s",dno);
printf(" Enter Street :");
scanf("%s",st);
printf(" Enter City :");
scanf("%s",city);
printf("\n Name : %s",name);
printf("\n Door no:%s",dno);
printf("\n street :%s",st);
printf("\n city :%s",city);
getch();
}

Write a program to read a character from keyboard and print its ASCII value.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("enter a character");
scanf("%c",&ch);
printf("The Equivalent ASCII value for the given characters is :%d",ch);
getch();
}

10
QUALITY COMPUTER EDUCATION

Write a program to read length and breadth or a rectangle and find its area and
perimeter.
#include<stdio.h>
#include<conio.h>
void main()
{
int l,b,area,peri;
clrscr();
printf("enter length of rectangle:");
scanf("%d",&l);
printf("enter breadth of rectangle:");
scanf("%d",&b);
area=l*b;
peri=
printf("The area of the rectangle:%d",area);
printf("The perimeter of the rectangle:%d",perm);
getch();
}

WAP to convert the given number is ASCII character


#include <stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a value:");
scanf("%d",&n); /* char ch; ch=n;*/
printf("\n The ASCII charcter is:%c",n);
getch();
}

Write a program to read radius of a circle and find area and circumference.
#include<stdio.h>
#include<conio.h>
void main()
{
int r,area,cir;
clrscr();
printf("enter radius of the circle:");
scanf("%d",&r);
area=(3.14*r*r); cir=(2*3.14*r);
printf("The area of the circle:%d",area);
printf("The circumference of the circle:%d",cir);
getch();

11
QUALITY COMPUTER EDUCATION

Program to find addition, subtraction, multiplication, division and modulus of two


numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,e,g;
float f;
clrscr();
printf("enter two numbers");
scanf("%d%d",&a,&b);
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=(float)a%b;
printf("\n sum of two numbers:%d",c);
printf("\n sub of two numbers:%d",d);
printf("\n multiplication of two numbers:%d",e);
printf("\n division of two numbers:%d",f);
printf("\n modulus of two numbers:%d",g);
getch();
}

Program to convert centigrade to Fahrenheit


# include <stdio.h>
# include <conio.h>
void main()
{
int c,f;
clrscr();
printf("enter the value of centigrade");
scanf("%d",&c);
f=(9*c/5)+32;
printf(" the value in Fahrenheit is %d",f);
getch();
}

program to swap two numbers using intermediate variable


#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c;

12
QUALITY COMPUTER EDUCATION

clrscr();
printf(“Enter two number”);
scanf(“%d%d”,&a,&b);
c=a;
a=b;
b=c;
printf(“After swapping the values are :%d %d”,a,b);
getch();
}

program to swap two numbers without using intermediate variable


#include <stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter two number”);
scanf(“%d%d”,&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf(“After swapping the values are :%d %d”,a,b);
getch();
}

program to find the biggest of 2 numbers using conditional operator


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("enter first value");
scanf("%d",&a);
printf("enter second value");
scanf("%d",&b);
max=(a>b)?a:b;
printf("max value :%d",max);
getch();
}

program to find the biggest of 3 numbers using conditional operator


#include<stdio.h>
#include<conio.h>
void main()

13
QUALITY COMPUTER EDUCATION

{
int a,b,c,x,y;
clrscr();
printf("enter three values");
scanf("%d%d%d",&a,&b,&c);
x=(a>b)?a:b;
y=(x>c)?x:c;
printf("max value:%d",y);
getch();
}

WAP to find the smallest of 5 numbers using ternary operator (or) conditional
operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,e,x,y,z,p;
clrscr();
printf("Enter five values");
scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
x=(a<b)?a:b;
y=(c<d)?c:d;
z=(x<y)?x:y;
p=(z<e)?z:e;
printf("\n The smallest value is :%d",p);
getch();
}

WAP to accept customer number, customer name, previous month reading, current
month reading and find total number of units and net payment at the cost of 5.65
Rs. per unit.
#include <stdio.h>
#include <conio.h>
void main()
{
int cno,pmr,cmr,units;
char cname[50];
float netpay;
clrscr();
printf("Enter customer number:");
scanf("%d",&cno);
printf(" Enter customer name:");
scanf("%s",cname);
printf(" Enter Current Month Reading");
scanf("%d",&cmr);

14
QUALITY COMPUTER EDUCATION

printf("Enter previous month reading");


scanf("%d",&pmr);
units=cmr-pmr;
netpay=5.65*units;
printf("\n Total units :%d",units);
printf("\n Net Payment:%0.2f",netpay);
getch();
}

program for the demo on increment operator


#include<stdio.h>
#include<conio.h>
void main()
{
int i=65,j=57,a;
clrscr();
a=++i;
printf("\n the value after pre increment :%d",a);
a=j++;
printf ("\n the value after post increment:%d",a);
a=j;
printf("\n the value after post increment in next statement:%d",a);
getch();
}

output: the value after pre increment : 66


the value after post increment:57
the value after post increment in next statement: 58

15
QUALITY COMPUTER EDUCATION

Control statements
It is used to execute the block of statement as per the user requirement. It is classified into
four types. They are
1) Conditional statements
2) Un conditional statements
3) Decision making statements
4) Looping statements

1) conditional statements: The if-statement is known as conditional statement as it


executes the statements based on the condition in if-statement.

a) if-statement: if the given condition in if-statement is true then the


statements following if-statement will be executed. Otherwise it will not
execute the statements
syntax: if (condition)
{
statement(s);
}

b) if-else statement: it is similar to the if-statement, the only difference is


that if the condition in if-statement is false then the statements following
else-statement will be executed.
syntax: if (condition)
{
statement(s);
}
else
{
statement(s);
}

c) Nested-if statement: The main purpose of using this statement is to


provide more conditions in the if-statements so that the user can execute
the required statements.
syntax: if (condition 1)
{
statement(s);
}
else if (condition 2)
{
statement(s);
}
- - - - - - -
else
{

16
QUALITY COMPUTER EDUCATION

statement(s);
}

2) Unconditional statement: Generally it should not be supported because it makes


the user confuse about the program because it moves the control to the another
location. They should be used only within the control statements otherwise the
user may not get perfect requirement. It is classified into three types. They are

a) goto statement: It moves the control to the required statement based on


label name. Same label name should not be used twice and number of goto
statements should not used otherwise the programmer may confuse. Label
name can be used before or after the goto statement.
Syntax: goto <label-name>;
- - - ----
<label-name>:

b) Continue statement: The block of statements will be executed


continuously with out breaking the loop.
Syntax: continue;

c) break statement: it is used to move the control outside of the control


statements.
Syntax: break;

3) Decision Making Statement: It is also known as Multi-way Branching


Statement. It consists of an expression in switch case and the constant values in
case statements. A Decision Making Statement can have number of case-
statements based on the bytes occupied by a variable.

If the expression in switch statement matches with the constant value in


the case statement, then the statement after case statement will be executed. It
consists of default statement, which is used to execute the statements if all the
constant values in case-statement does not match with the switch expression. To
execute the statements only in a single case-statement then break statement should
be used so that after executing the statements in the control terminates from the
Decision Making Statement.

Syntax: switch (expression)


{
case constant-1:
statement(s);
case constant-2:

17
QUALITY COMPUTER EDUCATION

statement(s);
- - - -
case constant-n:
statement(s);
default :
statement(s);
}

4. looping statements: It is used to execute the block of statements continuously as


long as the condition is true. It is classified into three types. They are
a) for loop
b) while loop
c) do-while loop

a) For loop: The for loop contains initial/final value, condition and
increment/decrement value. Basing on them the statements within the for
loop will be executed. Expressions can be ignored by using the semicolons.
Syntax: for(<expression1>;<expression2>;<expression3>
{
statement(s);
}
expression-1: it consists of initial value or final value
expression-2: It consists of condition
expression-3: It consists of increment/decrement value

It also allows Nested for-loop. A for-loop within another for-loop is


known as nested for-loop. It includes more expressions.
Syntax:
for(<exp-1a>,<exp-1b>;<exp-2a>,<exp-2b>;<exp-3a>,<exp-3b>)
{
statement(s);
}

b) While loop: It contains only the expression (condition). The loop will be
executed as long as the condition is true. Nested while-loop is also allowed.
Syntax: while(condition)
{
statement(s);
}

c) Do-while loop: After executing the statements for the first time then it will
check the condition. It will execute the statements as long as the condition is
true. The main purpose of using do-while loop is to execute the block of
statements at least once even though the condition is false.
Syntax: do
{

18
QUALITY COMPUTER EDUCATION

statement(s);
}
while(condition);

Program to check whether the given number is equal or not


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter three numbers");
scanf("%d%d%d",&a,&b,&c);
if(a==b&&b==c)
printf("the values are equal");
else
printf("the values are not equal");
getch();
}

Program to check whether the given number is even or odd


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a value: ");
scanf("%d",&n);
if (n%2==0)
printf("It is even");
else
printf("It is odd");

}
getch();
}

Program to find the biggest of 3 numbers


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter three numbers");

19
QUALITY COMPUTER EDUCATION

scanf("%d%d%d",&a,&b,&c);
if (a>b && a>c)
{
printf("the biggest number is:%d",a);
}
else if(b>a && b>c)
{
printf(" the biggest number is:%d",b);
}
else
{
printf(" the biggest number is:%d",c);
}
getch();
}

program to find whether the given number is positive, negative or zero


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf ("enter one number");
scanf("%d",&n);
if (n>0)
{
printf("the no is positive:%d",n);
}
else
if (n<0)
{
printf ("the no is negative:%d",n);
}
else
{
printf ("the no is equal to zero:%d",n);
}
getch();
}

Program to accept gender and find whether he/she is eligible for voting or not
#include<stdio.h>
#include<conio.h>
void main()
{

20
QUALITY COMPUTER EDUCATION

char gender;
clrscr();
printf("enter gender");
scanf("%c",&gender);
if(gender=='m')
printf("the eligible age is 21");
else if(gender=='f')
printf("the eligible age is 18");
else
printf("check your gender");
getch();
}

Program to accept gender and age and find whether he/she is eligible for voting or
not
#include<stdio.h>
#include<conio.h>
void main()
{
char gender;
int age;
clrscr();
printf("enter gender");
scanf("%c",&gender);
printf("Enter Age");
scanf("%d",&age);
if(gender=='m' || gender=='M')
{ if(age>=21)
printf("He is Eligible for voting");
else
prinf("He is Not eligible for voting");
}
else if(gender=='f' || gender=='F')
{ if(age>=18)
printf("She is Eligible for voting");
else
prinf("She is Not eligible for voting");
}
else
{
printf("Wrong input");
}
getch();
}

the above program using switch-case

21
QUALITY COMPUTER EDUCATION

/* switch(n%2)
{
case 0: printf("It is even");
case 1: printf("It is odd");

WAP to find Quadratic Roots


#include<stdio.h>
#include<conio.h>
#include <math.h>
void main()
{
int a,b,c,d;
float x1,x2;
clrscr();
printf("Enter values for a,b,c");
scanf("%d%d%d",&a,&b,&c);
d=(b*b)-(4*a*c);
if (d==0)
{
printf("\n Roots are real & equal");
x1=x2=-b/(2*a);
printf("\n The two roots are:%f\t%f" ,x1,x2);
}
else if (d>0)
{
printf("\n Roots are real & unequal");
x1=(-b+sqrt(d) )/(2*a);
x2=(-b-sqrt(d) )/(2*a);
printf("\n The two roots are:%f\t%f",x1,x2);
}
else
{
printf("\n Roots are imaginary");
x1=-b/(2*a);
x2=sqrt(d)/(2*a);
printf("\n First root: %f+i(%f)",x1,x2);
printf("\n Second root: %f-i(%f)",x1,x2);
}
getch();
}

Program to accept employ number, employ name, basic salary and calculate ta,da,
hra, pf, it, net salary, gross salary (if-statement)
#include<stdio.h>
#include<conio.h>
void main()

22
QUALITY COMPUTER EDUCATION

{
char ename[10];
int eno;
float ta,da,hra,pf,it,nsal,gsal,basic;
clrscr();
printf("Enter employ number");
scanf("%d",&eno);
printf("Enter Employ Name");
scanf("%s",ename);
printf("Enter Basic salary");
scanf("%f",&basic);
if (basic<=5000)
{
ta=(6.8*basic)/100;
da=(5.8*basic)/100;
hra=(6.9*basic)/100;
pf=(12.5*basic)/100;
it=(10*basic)/100;
}
else if (basic>5000 && basic<=10000)
{
ta=(8.9*basic)/100;
da=(12.8*basic)/100;
hra=(9.9*basic)/100;
pf=(11.5*basic)/100;
it=(12*basic)/100;
}
else if (basic>10000 && basic<=20000)
{
ta=(12.8*basic)/100;
da=(15.8*basic)/100;
hra=(16.9*basic)/100;
pf=(17.5*basic)/100;
it=(15.9*basic)/100;
}
else if (basic>20000)
{
ta=(15.8*basic)/100;
da=(16.8*basic)/100;
hra=(19.8*basic)/100;
pf=(19.5*basic)/100;
it=(18.99*basic)/100;
}
gsal=basic+ta+da+hra;
nsal=gsal-it-pf;
clrscr();

23
QUALITY COMPUTER EDUCATION

printf("\n The employ number:%d",eno);


printf("\n The employ name:%s",ename);
printf("\n The Basic Salary:%0.2f",basic);
printf("\n The Travelling allowance:%0.2f",ta);
printf("\n The Dearness allowance:%0.2f",da);
printf("\n The Provident fund:%0.2f",pf);
printf("\n The Income Tax:%0.2f",it);
printf("\n The House Rent Alowance:%0.2f",hra);
printf("\n The Gross Salary:%0.2f",gsal);
printf("\n The Net Salary:%0.2f",nsal);
getch();
}

write a program to accept 3 sides and check whether it is right angled triangle,
obtuse angled triangle, acute angled triangle, scalene triangle, equivaleteral triangle
or isosceles triangle
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max,x,y;
clrscr();
printf("Enter values for three sides"):
scanf("%d%d%d",&a,&b,&c);
if (a>b && a>c)
{
max=a;
x=b;
y=c;
}
else if (b>a && b>c)
{
max=b;
x=a;
y=c;
}
else
{
max=c;
x=a;
y=b;
}
if (max<(a+b))
{
if ( (max*max)=(x*x)+(y*y) )
printf("\n It is Right angled triangle");

24
QUALITY COMPUTER EDUCATION

else if ( (max*max)>(x*x)+(y*y) )
printf("\n It is Obtuse angled triangle");
else
printf("\n It is Acute angled triangle");
if(a==b==c)
printf("\n It is Equilateral triangle");
else if(a==b || b==c || c==a)
printf("\n It is Isosceles triangle");
else
printf("\n It is Scalene triangle");
}
else
{
printf(“It is not a triangle”);
}
getch();
}

Program to display the equivalent day for the given value(1-7) (switch-case)
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number(1-7)");
scanf("%d",&n);
switch(n)
{
case 1: printf("\n Sunday");break;
case 2: printf("\n Monday");break;
case 3: printf("\n Tuesday");break;
case 4: printf("\n Wednesday");break;
case 5: printf("\n Thursday");break;
case 6: printf("\n Friday");break;
case 7: printf("\n Saturday");break;
default: printf("Wrong input");
}
getch();
}

#include<stdio.h>
#include<conio.h>
void main()
{
int n;

25
QUALITY COMPUTER EDUCATION

clrscr();
printf("Enter a number(1-7)");
scanf("%d",&n);
switch(n)
{
case 1: printf("\n Sunday");
case 2: printf("\n Monday");
case 3: printf("\n Tuesday");
case 4: printf("\n Wednesday");
case 5: printf("\n Thursday");
case 6: printf("\n Friday");
case 7: printf("\n Saturday");break;
default: printf("Wrong input");
}
getch();
}

WAP to check whether the given character is vowel or consonant


#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character");
scanf("%c",&ch);
switch(ch)
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
printf("It is vowel");break;
default: printf("It is consonant");break;
}
getch();
}

Program to display the day for the given date in august 2002 (switch-case)
#include<stdio.h>
#include<conio.h>
void main()
{
int date;
clrscr();

26
QUALITY COMPUTER EDUCATION

printf("Enter date in August 2002(1-31)");


scanf("%d",&date);
if (date>=1 && date<=31)
{
switch(date%7)
{
case 1: printf("\n Thursday");break;
case 2: printf("\n Friday");break;
case 3: printf("\n Saturday");break;
case 4: printf("\n Sunday");break;
case 5: printf("\n Monday");break;
case 6: printf("\n Tuesday");break;
case 0: printf("\n Wednesday");break;
}
}
else
{
printf("Wrong input ! Try again");
}
getch();
}

WAP to print the natural numbers (goto-statement)


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter the final value");
scanf("%d",&n);
printf("The natural numbers are \n");
natural:
if(i<=n)
{
printf("%5d",i); i++;
goto natural;
}
getch();
}

WAP to find the factorial of the given number (for-loop)


// 5!=120 (1*2*3*4*5)
#include <stdio.h>
#include<conio.h>
void main()

27
QUALITY COMPUTER EDUCATION

{
long int n,i,f=1;
clrscr();
printf("Enter a value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n The factorial of given no: %ld",f);
getch();
}

WAP to find the sum and count of even, odd and natural numbers for the given
number
#include <stdio.h>
#include<conio.h>
void main()
{
int n,i,esum,osum,nsum,ecount,ocount,ncount;
clrscr();
esum=osum=nsum=ecount=ocount=ncount=0;
printf("Enter the final value");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
{
ecount=ecount+1;
esum=esum+i;
}
else
{
ocount=ocount+1;
osum=osum+i;
}
}
nsum=esum+osum;
ncount=ecount+ocount;
printf("\n sum of even nos: %d",esum);
printf("\n sum of odd nos: %d",osum);
printf("\n sum of natural nos: %d",nsum);
printf("\n count of even nos: %d",ecount);
printf("\n count of odd nos: %d",ocount);
printf("\n count of natural nos: %d",ncount);
getch();

28
QUALITY COMPUTER EDUCATION

WAP to find whether the given number is prime or not


#include <stdio.h>
#include<conio.h>
void main()
{
int i,n,c=0;
clrscr();
printf("Enter a number");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
c=c+1;
}
if(c= =2)
printf("it is prime no");
else
printf("it is composite no");
getch();
}

WAP to the multiplication table of the given number


#include <stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter a value");
scanf("%d",&n);
for(i=1;i<=20;i++)
{
printf("\n %5d*%5d=%5d",n,i,n*i);
}
getch();
}

WAP to print 20 multiplication tables upto 12 values


#include <stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();

29
QUALITY COMPUTER EDUCATION

for(i=1;i<=20;i++)
{
for(j=1;j<=12;j++)
{
printf("\n %5d*%5d=%5d",i,j,i*j);
}
printf("\n\n\n\n\n Press any key to continue");
getch();
clrscr();
}
}

program to find simple interest and compound interest


#include<stdio.h>
#include<conio.h>
void main()
{
float p,r,s,c;
int n,i=1;
clrscr();
printf("\n Enter the principle amount.");
scanf("%f",&p);
printf("\n Enter the rate of interest in %.");
scanf("%f",&r);
printf("\n Enter the time in years.");
scanf("%d",&n);
s=(p*n*r)/100;
printf("\n Rs.%f is the simple interest.",s);
while(i<=n)
{ c=p*(1+(r/100));
p=c;
i++;
}
printf("\nRs.%f is the compound interest.",c);
getch();
}

WAP to check whether the given number is armstrong or not


def: if the given number is equal to the sum of the cubes of individual digits then it is
known as armstrong
ex: 407,153=13 + 53 + 33 = 1 + 125 + 27 = 153
#include<stdio.h>
#include<conio.h>
void main()
{
int r,s=0,n,m;

30
QUALITY COMPUTER EDUCATION

clrscr();
printf("Enter a number");
scanf("%d",&n);
m=n;
while(n>0)
{
r=n%10;
n=n/10;
s=s+(r*r*r);
}
if (m==s)
printf("The number is Armstrong");
else
printf("The number is not a Armstrong");
getch();
}

WAP to print the following series


12345
12345
12345
12345
12345
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<5;j++)
{
printf("%5d",i);
}
printf("\n");
}
getch();
}

WAP to print the following series


11111
22222
33333
44444
55555

31
QUALITY COMPUTER EDUCATION

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
printf("%5d",i);
}
printf("\n");
}
getch();
}

WAP to find the value of the following series for the given value 1!+2!+3!+..............
#include<conio.h>
void main()
{
long int i,j,n,f,sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i;j++)
{
f=f*j;
}
sum=sum+f;
}
printf("The value for the series is :%`ld",sum);
getch();
}

WAP to find the value of the following series


-12+22 -32 +4 2 –52 .........

#include<stdio.h>
#include<conio.h>
void main()
{
long int i,j,n,f,sum=0;

32
QUALITY COMPUTER EDUCATION

clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
if (i%2==0)
sum=sum+(i*i) ;
else
sum=sum-(i*i);
}
printf("The value for the series is :%ld",sum);
getch();
}

1/2 +2/3+3/4+4/5+...........
#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n;
float sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
sum=sum+(float) ( i/ (i+1) );
}
printf("The value for the series is :%f",sum);
getch();
}

-1/2 + 3/4 - 5/6 + 7/8 ...........


#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n;
float sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i+=2)
{
if((i+1)%4= =0)
sum=sum+(float)( i/ (i+1) );

33
QUALITY COMPUTER EDUCATION

else
sum=sum-(float) ( i/ (i+1) );
}
printf("The value for the series is :%f",sum);
getch();
}

-1 + 2 - 3 + 4 - 5 + 6 .......
#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n,sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
sum=sum+ i;
else
sum=sum- i;
}
printf("The value for the series is :%d",sum);
getch();
}

WAP to find the value of the following series


1/3-2/4+3/5-4/6............
#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n;
float sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
sum=sum-(float)( i/ (i+2) );
else
sum=sum+(float) ( i/ (i+2) );
}
printf("The value for the series is :%f",sum);

34
QUALITY COMPUTER EDUCATION

getch();
}

1+2+4+7+11+…………
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,i,n,k=0;
clrscr();
printf("Enter a value");
scanf("%d",&n);
for(i=1;i<=n;i=i+k)
{
k++;
printf("%5d",i);
sum=sum+i;

}
printf("\n The value is:%d",sum);
getch();
}

WAP to print the following series


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%5d",j);
}
printf("\n");
}
getch();
}

35
QUALITY COMPUTER EDUCATION

WAP to print the following series


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;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%5d",i);
}
printf("\n");
}
getch();
}

WAP to print the following series


ravi
ravi ravi
ravi ravi ravi
ravi ravi ravi ravi
ravi ravi ravi ravi ravi

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("ravi \t");
}
printf("\n");
}
getch();
}

36
QUALITY COMPUTER EDUCATION

WAP to print the following series



☺☺
☺☺☺
☺☺☺☺
☺☺☺☺☺
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%c\t",2);
}
printf("\n");
}
getch();
}

WAP to print the following series


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

#include<conio.h>
void main()
{
int i,j,k=1;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t",k++);
}
printf("\n");
}
getch();
}

37
QUALITY COMPUTER EDUCATION

WAP to print the following series


1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 24
26 27 28 29 30
#include<conio.h>
void main()
{
int i,j,k=1;
clrscr();
for(i=1;i<=6;i++)
{
for(j=1;j<=5;j++)
{
printf("%d\t",k++);
}
printf("\n");
}
getch();
}

WAP to print the following series


1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf("%d\t",j);
}
printf("\n");
}
getch();
}

38
QUALITY COMPUTER EDUCATION

WAP to print the following series


1
2 2
3 3 3
4 4 4 4
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,p=40;
clrscr();
printf("ENTER THE VALUES OF N:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for (j=1;j<=p;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
p-=2;
printf("\n");
}
getch();
}

WAP to print the following series


ravi
rav
ra
r
#include”conio.h”
#include"stdio.h"
void main()
{
int i,j,l;
char n[15];
clrscr();
printf("\n Enter the string.");
scanf("%s",&n);
for(i=0;n[i]!='\0';i++);
l=i;
for(i=l;i>=0;i--)

39
QUALITY COMPUTER EDUCATION

{
for(j=i;j>=0;j--)
{
printf("%c",n[j]);
}
printf("\n");
}
getch();
}

WAP to print the following series


ivar
iva
iv
i
#include"stdio.h"
void main()
{
int i,j,k,l=0;
char n[30];
clrscr();
printf("\n Enter the string.");
scanf("%s",&n);
strrev(n);
for(i=0;n[i]!='\0';i++)
l=i;
for(i=0;i<l;i++)
{
for(j=i;j>=0;j--)
{
printf("%c",n[j]);
}
printf("\n");
}
getch();
}

WAP to print the following series


i
vi
avi

40
QUALITY COMPUTER EDUCATION

ravi
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,l=0;
char n[30];
clrscr();
printf("enter a string\n");
scanf("%s",n);
strrev(n);
for(i=0;n[i]!='\0';i++)
{
l++;
}
for(i=l;i>=0;i--)
{
for(j=0;j<i;j++)
{
printf("%c",n[j]);
}
printf("\n");
}
getch();
}

WAP to print the following series


ivar
iva
iv
i
#include"stdio.h"

41
QUALITY COMPUTER EDUCATION

void main()
{
int i,j;
char n[30];
clrscr();
printf("\n Enter the string.");
scanf("%s",&n);
for (i=0;n[i]!='\0';i++)
for(j=0;j<=i;j++)
{
printf("\n %c %s",n[j],n);
}
getch();
}

searching techniques
program for linear search
# include<iostream.h>
# include<conio.h>
void main()
{
int flag = 1,i,a[100],k;
clrscr();
printf(“Enter how many elements”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the element to be searched”);
scanf(“%d”,&k);
for( i = 0; i< n; i++)
{
if(a[i] == k)
{
printf("\n Search is successful \n");
printf(“\n Element %d Found at Location : ",k,(i+1));
flag = 0 ;
}
}
if (flag)
printf( "\n Search is unsuccessful");
getch();
}

Program for binary search


Searching an element in the list of elements, which are in ascending order is the process
of binary search

42
QUALITY COMPUTER EDUCATION

# include<stdio.h>
# include<conio.h>
void main()
{
int flag=1,k,low=0,high,mid,n, a[200],i;
clrscr();
printf(“How many elements you want?”);
scanf(“%d”,&n);
high=n-1;
printf("\nEnter elements in Ascending order:\n ");
for(i=0;i<n;i++)
{
printf(“Enter the element:”);
scanf(“%d,&a[i]);
}
printf(“Enter element to be searched”);
scanf(“%d”,&k);
while(low <= high)
{
mid = (low + high)/2;
if( k < a[mid]) /* element in lower half*/
high = mid - 1 ;
else if(k > a[mid]) /* element in upper half*/
low = mid + 1 ;
else if(k == a[mid])
{
printf(“\n Search is successful \n)";
printf("\n Element %d Found at Location : ",k,(mid+1));
flag = 0 ;
break ;
}
}
if (flag)
printf( "\n Search is unsuccessful");
getch();
}

43
QUALITY COMPUTER EDUCATION

sorting techniques
The process of arranging the data either in ascending order or descending order is known
as sorting . sorting of data is done using 7 techniques
1) Bubble sort
2) Insertion sort
3) Selection sort
4) Merge sort
5) Quick sort
6) Radix sort
7) Heap sort

program for bubble sort


# include<stdio.h>
# include<conio.h>
void main()
{
int [200];
clrscr();
printf(“How many elements you want?”);
scanf(“%d”,&n);
high=n-1;
printf("\nEnter elements in Ascending order:\n ");
for(i=0;i<n;i++)
{
printf(“Enter the element:”);
scanf(“%d,&a[i]);
}

44
QUALITY COMPUTER EDUCATION

Unformatted input and output statements


1) input statements

a) gets(): it is used to accept a string until it founds return key (ente). the last
character is treated as NULL character and is indicated with NULL or '\0'
Syntax: gets(variable);
Example: gets(s);

b) getchar(): it is used to accept a single character into the variable.


Syntax: variable =getchar();
Ex: ch=getchar();

c) getch(): it is used to accept a single character into a variable which will not be
appeared on the screen.
Syntax: getch(variable);
Ex: getch(ch);

d) getche(): it is also used to accept a single character as similar to getchar(). The


main difference is that getche() is a macro where as getch() or getchar() are functions.
Syntax: getche(variable);
Ex: getche(ch);

2) output statements

a) puts(): it is used to display the string in the new line until it found enter key.
Syntax: puts(variable);
ex: puts(ch);

b) putchar(): it is used to display a single character.


Syntax: variable=putchar()
Ex: ch=putchar();

c) putche(), putch(): it is used to display a single character where putche() is a macro


and putch() is a function.
Syntax: putche(variable);
Syntax: putch(variable);
Ex: putch(s);

45
QUALITY COMPUTER EDUCATION

operations on strings
program to accept a name and find the length
#include<stdio.h>
#include<conio.h>
void main()

{
char s[50];
int i,l=0;
clrscr();
puts("enter a name");
gets(s);
for(i=0;s[i]!='\0';i++)
{
l++;
}
printf("the length of the string:%d",l);
getch();
}

WAP to check whether the given string is palendrome or not


#include <stdio.h>
#include <conio.h>
void main()
{
char s[50],s1[50];
int f=1,i,l=0,j=0;
clrscr();
puts("enter a string");
gets(s);
for(i=0;s[i]!='\0';i++)
l++;
for(i=l-1;i>=0;i--)
{ s1[j++]=s[i];
}
s1[j]='\0';
for(i=0;s[i]!='\0';i++)
{
if (s[i]!=s1[i])
{
f=0;
}
}
if (f==0)
puts("it is not a palendrome");

46
QUALITY COMPUTER EDUCATION

else
puts("it is a palendrome");
getch();
}

47
QUALITY COMPUTER EDUCATION

Functions
string functions
the header file is #include "string.h". it is used to accept a string and returns either string
or numeric value.
1) strlen(): to find the length of the string
EX: strlen("it is c"); 7
2) strrev(): to reverse the given string
ex: strrev("ravali"); ilavar
3) strcpy(): it is used to copy the string into a variable
ex: strcpy(result,"pass");
4) strupr(): converts the lower case characters in a string into upper case characters.
ex: strupr('Ravi'); RAVI
5) strlwr(): converts the upper case characters in a string into lower case characters.
ex: strlwr('Ravi'); ravi
6) strcmp(): compare the given two strings.
syntax: strcmp(string1,string2)
if string1=string2 then it returns 0
if string1>string2 then it returns positive
if string1<string2 then it returns negative
ex: strcmp("ravi","srinu") -1
7) stricmp() : ignores case

48
QUALITY COMPUTER EDUCATION

Library Functions
wap to accept base and exponent and find its value using library functions
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
float b,e;
clrscr();
printf("Enter base and exponent");
scanf("%f%f",&b,&e);
printf("The value is :%f",pow(b,e));
getch();
}

49
QUALITY COMPUTER EDUCATION

Storage Classes
It specifies the scope of the variables while specifying the data type. It is classified into 4
types. They are
1) Automatic varibles.
2) Static variables.
3) Register variables.
4) External variables.

1) Automatic variables: The value of the automatic variable will have effect only in a
function. It is the default type of storage class. Its initial value is garbage. The keyword is
"auto".
ex: int a,b; (or) auto int a,b;

2) External Variables: The value of the external variable will have effect in the entire
program. These variables should be declared globally. The keyword is "extern" and its
initial value is 0.

3) Static Variables: The value of the static variable will have effect in a function. The
keyword is "static" and its initial value is 0. They should be declared in a function.

4) Register variables: The value of the register variable will have effect through out the
program. The keyword is "register" and its initial value is garbage value. The main
advantage of using register variables is to store the values of the variables in the registers
for faster accessibility.

WAP for the demo on automatic variable


#include<stdio.h>
#include<conio.h>
void main()
{
auto int a; /* int a; */
void display();
clrscr();
printf("\n The Initial value of automatic variable is :%d",a);
a=5;
printf("\n The Specified value of automatic variable is :%d",a);
display();
}
void display()
{
int a;
printf("\n The value of automatic variable in another function is :%d",a);
}

output:
The Initial value of automatic variable: 998

50
QUALITY COMPUTER EDUCATION

The Specified value of automatic variable: 5


The value of automatic variable in another function: 996

WAP for the demo on register variables


#include<stdio.h>
#include<conio.h>
void main()
{
void disp();
register int a;
clrscr();
printf("\n The Initial value of register variable is :%d",a);
a=5;
printf("\n The Specified value of register variable is :%d",a);
disp();
getch();
}
void disp()
{
register int a;
printf("\n The Specified value of register variable is :%d",a);
}
output:
The Initial value of register variable: 998
The Specified value of register variable: 5
The value of register variable in another function: 5

WAP for the demo on extern variables


#include<stdio.h>
#include<conio.h>
int a;
void main()
{
extern int a;
void display();
clrscr();
printf("\n The Initial value of external variable is :%d",a);
a=5;
printf("\n The Specified value of external variable is :%d",a);
display();
getch();
}
void display()
{
extern int a;
printf("\n The value of external variable in another function is :%d",a);

51
QUALITY COMPUTER EDUCATION

output:
The Initial value of external variable: 0
The Specified value of external variable: 5
The value of external variable in another function: 5

WAP for the demo on static storage class


#include<stdio.h>
#include<conio.h>
void main()
{
static int a;
clrscr();
printf("\n The Initial value of static variable is :%d",a);
a=5;
printf("\n The Specified value of static variable is :%d",a);
display();
getch();
}
void display()
{
static int a;
printf("\n The value of static variable in another function is :%d",a);
}

output:
The Initial value of static variable: 0
The Specified value of static variable: 5
The value of static variable in another function: 0

52
QUALITY COMPUTER EDUCATION

POINTERS
A pointer is a variable which hold the address of another variable. The pointer variable is
indicated with pointer operator (*).

Declaration of pointer variable:


The pointer variable will be declared using * opeator in the required data type.
Syntax: <data type> *<variable>;
Example: int *p, x;
Here p is called as pointer variable and x is a variable.

Assigning address to pointer variable:


After declaring the pointer variable. The address of another variable should be
specified to the pointer variable.
Syntax: <pointer>=&<variable>
Example: p=&x;
For a pointer variable address operator (&) should not be specified.

Storing value into a pointer variable:


To store a value into the pointer variable pointer operator followed to pointer
variable should be used
Syntax: *<pointer>=<variable>
Example: *p=x;

Pointer arithmetic:
The arithmetical operators or increment and decrement operators will be used for
pointer arithmetic. It is used to change the address of the pointer variable
Ex: p++;
if the address of pointer p is 65536 then the address after pointer arithmetic is 65538 (if
its return type is int)

Displaying the address of pointer variable


To display the address of the pointer variable, the formatted character %u should
be used.
Ex: printf("\n Address is :%u",p);

Pointer to arrays:
A pointer can also point to an arrays, which may be single dimensional array or
double dimensional array.

Pointer to Single dimensional array:


For specifying single dimensional array the pointer will be taken as following
Syntax: *(pointer + value)
example: int *p;

* (p+0) * (p+1) *(p+2) *(p+3) *(p+4)

53
QUALITY COMPUTER EDUCATION

5 6 7 9 8
65536 65538 65540 65542 65544

pointer to double dimensional array


For specifying double dimensional array the variable should be declared as
double dimensional array and it is taken as following
Syntax: *(*(pointer + row)+column)
example: int *a[2][3];
*(*(a+0)+1)

*(*(a+0)+0) *(*(a+0)+1) *(*(a+0)+2)


4 5 6

7 8 9

*(*(a+1)+0) *(*(a+1)+1) *(*(a+1)+2)

pointer to functions
The address of the variable can be send as an arguments to the functions. In the
function these arguments will be used as a pointer. The main purpose of using this
concept is to make use of an addresses of a variable in other functions. and can change
the values of a variable without using return values.

Instead of sending values as an arguments, the programmer will send the


addresses as an argument.

Pointer to strings
The first address of a string will be used by a pointer and using this reference the
other cells of a string will be located until it founds NULL character. Pointing to next
memory cells will be proceded through pointer arithmetic.

pointer to pointer
A pointer can also point the other pointer variable by using the reference or address of
other pointer variable.
ex: int *p,a,**q;
This concept can be extended to number of pointer but it makes the programmer
confuse.

WAP to swap two numbers using pointer to functions


#include"stdio.h"
#include"conio.h"
void main()
{
int a,b;
void swap(int *,int *);

54
QUALITY COMPUTER EDUCATION

clrscr();
printf("Enter two values");
scanf("%d%d",&a,&b);
printf("\n Before swapping the values are: %d\t%d",a,b);
swap(&a,&b);
printf("\n After swapping the values are : %d\t%d",a,b);
getch();
}
void swap(int *p,int *q)
{
int t;
t=*p;
*p=*q;
*q=t;
}

WAP to find the length of a string using pointers to functions


#include <stdio.h>
#include <conio.h>
void main()
{
char s[50];
void length(char *);
clrscr();
puts("enter a string");
gets(s);
length(&s);
getch();
}
void length(char *s)
{
int i,l=0;
for(i=0;*s!='\0';i++)
{
l++;s++;
}
printf("The length is:%d",l);
}

WAP to display the address of a pointer variable by passing function as


pointer(pointers to functions)
#include"stdio.h"
#include"conio.h"
void main()
{
int *demo(void);

55
QUALITY COMPUTER EDUCATION

int *r;
clrscr();
r=demo();
printf("value of the address%u is %d",r,*r);
}
int *demo()
{
int p;
p=10;
return(&p);
}

DYNAMIC MEMORY ALLOCATIONS


It consists of calloc and malloc which are used to allocate the memory. It is used to save
the memory. These are available in the "alloc.h"

calloc(): it is used to allocate the number of bytes for a pointer variable


syntax: (type)calloc(value,sizeof(datatype))
ex: k=(int *)calloc(5,sizeof(int)) 10 bytes of memory

free(): it is used to refresh the memory cells.

malloc: it allocates the memory for the variable


syntax: malloc(size)
ex: malloc(10)

Program for the demo on calloc


#include<stdio.h>
#include<alloc.h>
#include<string.h>
#include<conio.h>
void main()
{
char *str=NULL;
str=(char*)calloc(10,sizeof(char));
clrscr();
strcpy(str,"hello");
printf("string is %s\n",str);
free(str);
}

output: the string is hello

program for the demo on alloc


#include<stdio.h>

56
QUALITY COMPUTER EDUCATION

#include<alloc.h>
#include<conio.h>
main()
{
void *ptr;
ptr=malloc(4);
clrscr();
if(ptr==NULL)
{
printf("memory is not allocated");
}
else
{
printf("memory is allocated");
}
}

output: Memory is allocated

program for the demo on malloc


#include<stdio.h>
#include<string.h>
#include<alloc.h>
#include<process.h>
#include<conio.h>
main()
{
char *str;
//allocate memory for string
str=(char *)malloc(10);
clrscr();
if(str==NULL)
{
printf("no memory to allocate buffer\n");
exit(1);
}
strcpy(str,"hello");
printf("string is %s\n",str);
free(str);
}

57
QUALITY COMPUTER EDUCATION

STRUCTURES
The collection of heterogeneous elements is known as structure. It is used to store the
contents of different data type in a single variable.
syntax: struct <structure-name>
{
data type 1: variable(s);
data type 2: variable(s);
- -
data type n: variable(s);
};
ex:
struct stud
{
int sno,age;
char sname[50],course[30];
};
the structure can be created either in the main function or outside the main function. The
variables in a structure is called as fields.

calling a structure in a function: The structure can be called using the reference of
structure name and the complete structure will be stored in a structure variable
syntax: struct <structure-name> <structure-var>;
ex: struct stud s;

accessing fields in a function: Using dot operator the fields in a structure can be called
using the structure variable.
syntax: <structure-var>.field
ex: s.sno;

passing arguments to structures: The arguments can be passed to the structure variable
while calling in the main function.
syntax: <structure-var>{argument(s)};
ex: s{10,20,"ravi","adse"};

structure to arrays: The structure variable can be used as an array type


by specifing the size
ex: struct student s[50];
it can take maximum of 50 student details from 0-49

To access the fields from a structure into the funtion use the following syntax:
syntax: var[value].field
example: s[0].sno;

nested structure: A structure within another structure is known as nested structure. A


structure can be created within another structure or a structure can be called within

58
QUALITY COMPUTER EDUCATION

another structure. The fields in the derived structure(inside structure) can be called using
the structure variable name of the base structure and derived structure.

pointers to structures: The structure variable can be used as a pointer


variable by using pointer operator and its field will be accessed using
the operator -> or .( )
ex: s->sno;

WAP to accept employee details and display them using structures


#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
struct emp e;
clrscr();
printf("enter employ number");
scanf("%d",&e.eno);
printf("Enter employ name");
scanf("%s",e.ename);
printf("Enter Basic salary");
scanf("%d",&e.basic);

printf("The employ details is \n");


printf("\n employ number :%d",e.eno);
printf("\n employ name :%s",e.ename);
printf("\n Basic salary :%d",e.basic);
getch();
}

WAP to find the sum of two numbers using arguments in a structure


#include"stdio.h"
#include"conio.h"
struct add
{
int a,b,c;
};
void main()
{
struct add x={5,6};
clrscr();
x.c=x.a+x.b;

59
QUALITY COMPUTER EDUCATION

printf("Sum of the elements :%d",x.c);


getch();
}

WAP to accept number of employee details and search a employ detail(structure to


arrays)
//using structures to arrays
#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
int n,i,k,f=0;
struct emp e[20];
clrscr();
printf("How many Employ Details you want to accept :");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("enter employ number :");
scanf("%d",&e[i].eno);
printf("Enter employ name :");
scanf("%s",e[i].ename);
printf("Enter Basic salary :");
scanf("%d",&e[i].basic);
}
printf("Enter employ number to search :");
scanf("%d",&k);
for(i=0;i<n;i++)
{
if(e[i].eno==k)
{
printf("\n The employ details is \n");
printf("\n employ number :%d",e[i].eno);
printf("\n employ name :%s",e[i].ename);
printf("\n Basic salary :%d",e[i].basic);
f=1;
}
}
if(f==0)
printf("\n Employ Number not found");

60
QUALITY COMPUTER EDUCATION

getch();
}

WAP for the demo to pass structure variable as an argument (structure to functions)
#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
struct emp e;
void disp(struct emp e);
clrscr();
printf("enter employ number");
scanf("%d",&e.eno);
printf("Enter employ name");
scanf("%s",e.ename);
printf("Enter Basic salary");
scanf("%d",&e.basic);
disp(e);
getch();
}
void disp(struct emp e)
{
printf("\n\n The employ details is \n");
printf("\n employ number :%d",e.eno);
printf("\n employ name :%s",e.ename);
printf("\n Basic salary :%d",e.basic);
}

61
QUALITY COMPUTER EDUCATION

WAP for the demo to pass pointer to structure as an argument.


#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
struct emp *e;
void disp(struct emp *);
clrscr();
printf("enter employ number");
scanf("%d",&e->eno);
printf("Enter employ name");
scanf("%s",e->ename);
printf("Enter Basic salary");
scanf("%d",&e->basic);
disp(e);
getch();
}
void disp(struct emp *e)
{
printf("\n\n The employ details is \n");
printf("\n employ number :%d",e->eno);
printf("\n employ name :%s",e->ename);
printf("\n Basic salary :%d",e->basic);
}

//WAP to create student details using nested structures


#include<stdio.h>
struct date
{
int dd,mm,yy;
};
struct stud
{
int sno;
char sname[10];
int age;
struct date d;
}s;
void main()
{
clrscr();

62
QUALITY COMPUTER EDUCATION

printf("Enter student number");


scanf("%d",&s.sno);
printf("Enter student name");
scanf("%s",s.sname);
printf("Enter student age");
scanf("%d",&s.age);
printf("Enter student date of birth(dd/mm/yy)");
scanf("%d%d%d",&s.d.dd,&s.d.mm,&s.d.yy);

printf("\n student number:%d",s.sno);


printf("\n student name :%s",s.sname);
printf("\n student age :%d",s.age);
printf("\n Date of birth :%d/%d/%d",s.d.dd,s.d.mm,s.d.yy);

getch();
}

63
QUALITY COMPUTER EDUCATION

FILES
It is used to store the output data of a file into a data file using files concept.
1) Sequential files
2) Random files

Sequential files
it is used to access the records orderly.

Declaration: To access(store and retrieve) the contents of different data type the pointer
variable should be taken and it is declared using the following syntax
syntax: FILE *pointer;
example: FILE *fp;

Opening a data file: To open a data file in the required mode fopen() should be used
syntax: pointer=fopen("datafile","mode");
example: fp=fopen("rk.dat","w");

closing a file: To close the file fclose() statement should be used.


syntax: fclose(pointer);
example: fclose(fp);

mode to open a file


r - Read mode, to read the contents from a file
w - Write mode, to write the records into a file,It creates a file and store the contents
in that file eventhough the file is existed.
a - Append mode, it is used to add the records in the existed file. If the file does not
exist then it will creates a new file and stores the records in them.
r+ - Open an existing file for update (reading and writing)
w+ - Create a new file for update (reading and writing). If a file by that name already
exists, it will be overwritten.
a+ -Open for append; open for update at the end of the file, or create if the file does
not exist.

file input and output statements


fscanf(): it is used to read the data from an existed data file. It is used for read mode.
syntax: fscanf(pointer,"formatted string",&var1,&var2....);
example: fscanf(fp,"%d%s%d",&sno,name,&fees);

fprintf: it is used to store the data into the data file. It is used for write or append mode.
syntax: fprintf(pointer,"formatted string",var1,var2....);
example: fprintf(fp,"%d%s%d",sno,name,fees);

feof(): file-end-of-file. It returns true when there is no contents in a file


ex: !feof(fp);

64
QUALITY COMPUTER EDUCATION

EOF: EOF indicated End Of File. The expression will becomes true if end of the file is
reached.

Random access files


fseek(): This function is used to move the file pointer to any specified position in a file.
This function itself cannot do any I/O operations, it moves the pointer forward or
backward in a file
syntax: fseek(fp,n,p);
where p is the position in a file, n is the long integer(returns number of bytes),
if p is 0- beginning of the file, 1- Current position, 2- end of file

ftell(): it returns current position of file pointer as a byte number into a long integer
syntax: n=ftell(fp);

unformatted Input and output functions

input statements
1) fgetc(): it is used read a character from the file.
ex: ch=fgetc(fp);

2) fgets(): it is used to read a string from the file.


ex: fgets(s,n,fp);
where s is a string variable

3) fread(): It is used to read data from the the file and copies it into the structure variable
ex: fread(&e, sizeof(e),1,fp);
where e is a structure variable

output statements
1) fputc(): it is used write a character into the file.
ex: fputc(ch,fp);

2) fputs(): it is used to write a string into the file.


ex: fputs(s,fp);
where s is a string variable

3) fwrite(): It is used to write data into the the file from the structure variable
ex: fread(e, sizeof(e),1,fp);
where e is a structure variable

Detecting errors
ferror(): It is a library function which is used to detect whether the contents is read
successful or not. It returns zero if the data in a file is successful found.
ex: if (ferror(fp)
{
printf("Data is not read successfully");

65
QUALITY COMPUTER EDUCATION

break;
}

Program to store student details in a file using write mode(sequential file)


#include<stdio.h>
#include<conio.h>
void main()
{
int i,roll;
char name[10];
int n;
FILE *fp;
fp=fopen("d.dat","w");
clrscr();
puts("for how many?");
scanf("%d",&n);
puts("enter student details");
for(i=0;i<n;i++)
{
scanf("%d%s",&roll,name);
fprintf(fp,"%d%5s",roll,name);
fprintf(fp,"\n");
}
fclose(fp);
getch();
}

program to write the data in a given file(sequential file)


# include "stdio.h"
# include "conio.h"
void main()
{
int cno,smr,emr;
char cname[30];
char fname[50];
FILE *fp;
clrscr();
printf("Enter file name");
gets(fname);
fp = fopen(fname,"w");
printf("Enter custno");
scanf("%d",&cno);
fflush(stdin);
while(cno != 0)
{
printf("Enter name : " );
gets(cname);

66
QUALITY COMPUTER EDUCATION

fflush(stdin);
printf("Enter smr");
scanf("%d",&smr);
fflush(stdin);
printf("Enter emr");
scanf("%d",&emr);
fflush(stdin);
fprintf(fp,"%3d %30s %3d %3d\n",cno,cname,smr,emr);
printf("Enter custno");
scanf("%d",&cno);
fflush(stdin);
}
fclose(fp);
}

program to read the data from a file(sequential file)


# include "stdio.h"
# include "conio.h"
void main()
{
int cno,smr,emr;
char cname[30];
FILE *fp;
clrscr();
fp = fopen("xyz.dat","r");
while(! feof(fp))
{
fscanf(fp,"%d %s %d %d\n",&cno,cname,&smr,&emr);
printf("%d %s %d %d\n",cno,cname,smr,emr);
}
fclose(fp);
getch();
}

WAP to accept student number, student name and age and store it in a file
using append mode(sequential file).
# include "stdio.h"
# include "conio.h"
void main()
{
int sno,age;
char sname[30],ch;
FILE *fp;
clrscr();
fp = fopen("ravi.dat","a");
do

67
QUALITY COMPUTER EDUCATION

{
printf("Enter Student number :");
scanf("%d",&sno);
fflush(stdin); // refresh the memory
printf("Enter Student name : " );
gets(sname);
printf("Enter age of the student:");
scanf("%d",&age);
fprintf(fp,"%d%s%d",sno,sname,age);
fflush(stdin);
printf("Do u want to continue (y/n):");
scanf("%c",&ch);
}
while(ch=='y' || ch =='Y');
fclose(fp);
getch();
}

WAP to read student number, student name and age from a file(sequential file)
# include "stdio.h"
# include "conio.h"
void main()
{
int sno,age;
char sname[30];
FILE *fp;
clrscr();
fp = fopen("ravi.dat","r");
while(!feof(fp)) //while file end of file is reached
{
fscanf(fp,"%d%s%d",&sno,sname,&age);
printf("\n Student number : %d",sno);
printf("\n Student name : %s",sname);
printf("\n Age of the student: %d",age);
}
fclose(fp);
getch();
}

program for storing data into a file using random files


#include <stdio.h>
#include <conio.h>
struct stud
{
int htno,age;
char name[30];

68
QUALITY COMPUTER EDUCATION

};
void main()
{
FILE *fp;
struct stud s;
char fname[30];
clrscr();
puts("Enter file name");
fflush(stdin);
gets(fname);
fp=fopen(fname,"w");
while(1)
{
printf("Enter Roll no (0-exit):");
scanf("%d",&s.htno);
if(s.htno==0) break;
printf("Enter Student Name:");
fflush(stdin);
gets(s.name);
printf("Enter Age of the Student:");
scanf("%d",&s.age);
fwrite(&s,sizeof(s),1,fp);
}
fclose(fp);
getch();
}

program for displaying records from a file


#include <stdio.h>
#include <conio.h>
struct stud
{
int htno,age;
char name[30];
};
void main()
{
FILE *fp;
struct stud s;
char fname[30];
clrscr();
puts("Enter file name");
fflush(stdin);
gets(fname);
fp=fopen(fname,"r");
while(fread(&s,sizeof(s),1,fp)==1)

69
QUALITY COMPUTER EDUCATION

{
printf("%d\t%s\t%d\n",s.htno,s.name,s.age);
}
fclose(fp);
getch();
}

70
QUALITY COMPUTER EDUCATION

COMMAND LINE ARGUMENTS


Passing arguments to the main function from the command prompt is known as command
line argument
ex: main(int argc[],char *argv[])
argc = argument count is used to count the number of arguments in the command
prompt.
argv = argument variables, to refer an argument in the command prompt
atoi = ascii to integer

c:\>cla 50 60
[0] [1] [2]

WAP to print natural numbers for the given number


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main(int argc,char *argv[])
{
int i;
clrscr();
for(i=0;i<=atoi(argv[1]);i++)
{
printf("%5d",i);
}
getch();
}

program to compare whether the given two strings are equal or not
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc[],char *argv[])
{
int i;
clrscr();
printf("\n %s",argv[1]);
printf("\n %s",argv[2]);
if(strcmp(argv[1],argv[2]) == 0)
printf("\n Both are equal");
else
printf("\n not equal");
getch();
}

program to display the given arguments with position


#include<stdio.h>

71
QUALITY COMPUTER EDUCATION

#include<conio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
int i;
clrscr();
printf("no of arguments are%d",argc-1);
for(i=1;i<argc;i++)
printf("\narg[%d]=%d",i,atoi(argv[i]));
getch();
}

72
QUALITY COMPUTER EDUCATION

C-GRAPHICS

gotoxy(): it is used to move the cursor to the required column and row
position
gotoxy(x,y); x=columns,y=rows
gotoxy(50,10);

delay: it is used to specify the speed of the execution of some instructions. Its header file
is #include<dos.h>

delay(milliseconds);
delay(200);

program to move the text from left to right


#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int i;
clrscr();
for(i=0;i<=70;i++)
{
gotoxy(i,10);printf(" Aptech ");
delay(50);
}
}

#include<graphics.h> is used to support the graphics keywords in the program

cleardevice() : To clear the graphics screen

initgraph() : It is used to initialize the graphics


syntax: initgraph(&graph_drivers,&graph_mode,"path");

graphics_drivers : to use the adapters such as MGA, CGA, EGA, MCGA,


VGA, SVGA, DETECT (get colors)

graphics_mode : To set the number of pixels for filling color or


graphics
text -24*80
graphics-480*640

example: initgraph(&gd,&gm,"c:\\tc\\bgi");

text=24*80 pixel=480*640

73
QUALITY COMPUTER EDUCATION

sound: It is used to set sound in milliseconds. Its header file is #include<dos.h>. It is


necessary to used nosound() so that the sound can be stopped.

syntax: sound(milliseconds);

settextstyle(): it is used to set the text style, fonts and direction


syntax: settextstyle(font,direction,size);

outtextxy(): it is used to display the string in the specified row and column.
syntax: outtextxy(column,row,"string");
(or)
outtextxy(x,y,"string");

putpixel: it is fill a specified pixel with color


syntax: putpixel(x,y,color);

random: it is used to pick a value automatically basing on the specified final value. its
header file is #include<stdlib.h>
Syntax: random(value);

setfillstyle: it is used to fill the pixel with specified style(0-12).


Syntax: setfillstyle(style,color)

pieslice: it is used to draw a pie


Syntax: pieslice(x,y,sangle,eangle,radius)
sangle-starting angle
eangle-ending angle

circle: it is used to draw a circle in the required location with the specified radius.
Syntax: circle(x,y,radius);
Ex: circle(320,240,10);
(320,240) gives the location of center point of circle.

rectangle: it is used to draw a rectangle


Syntax: rectangle(x,y,x1,y1);
Ex: rectangle(20,20,300,300);
(x,y) - starting position
(x1,y1)-ending position

ellipse: it is used to draw ellipse.


Syntax: ellipse(x,y,sangle,eangle,xradius,yradius)
sangle- starting angle
eangle-ending angle

74
QUALITY COMPUTER EDUCATION

kbhit(): key board hit. It is used to run the graphics until any key is pressed in
keyboard.
program to move the text from left to right with graphics
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void main()
{
int gd=DETECT,gm=0,i;
clrscr();
initgraph(&gd,&gm,"c:\\tc\\bin");
setbkcolor(RED); //Setting background color
setcolor(WHITE); //Setting foreground color
for(i=0;i<=70;i++)
{
gotoxy(i,10);printf(" Aptech ");
delay(50);
}
}

Program for the demo on graphics


# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0;
initgraph(&gd,&gm,"c:\\tc\\bgi");// path to bgi files
cleardevice();
setbkcolor(BLUE); //setting background color of screen
setcolor(YELLOW); //setting foreground color
printf("\t x = %d",getmaxx());//displaying maximum pixels in x-axis(columns)
printf("\t y = %d",getmaxy());//displaying maximum pixels in y-axis(rows)

line(320,0,320,480); //displaying line(x,y,x1,y1)


line(0,240,640,240);

circle(320,240,10); //circle(x,y,radius)
arc(320,240,0,360,50); //arc(x,y,x1,y1,radius)
arc(320,240,180,360,100);
setfillstyle(6,YELLOW); //text style

pieslice(490,100,90,270,70);
rectangle(50,50,150,80); //rectangle(x,y,x1,y1);
rectangle(220,140,420,340);

75
QUALITY COMPUTER EDUCATION

setfillstyle(5,GREEN);
bar(500,150,550,200);
setfillstyle(1,BROWN);
bar(500,400,550,450);
bar3d(50,100,100,150,15,1);
bar3d(100,400,150,450,30,1);

getch();
closegraph();
cleardevice();
}

Program for name with different styles


# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0,i,r=20;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
for(i=0;i<=10;i++)
{
settextstyle(i,0,5);
outtextxy(0,r,"Aptech");
r = r + 30;
}
getch();
}

Program for displaying address with different styles


# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();

settextstyle(7,0,4); outtextxy(0,50,"GRK"); //0- HORIZ_DIR ,1-VERT_DIR


settextstyle(3,0,7);outtextxy(0,75,"19-168");
settextstyle(0,0,6);outtextxy(0,170,"GPT");
settextstyle(1,0,6);outtextxy(0,225,"VSP");
getch();

76
QUALITY COMPUTER EDUCATION

cleardevice();
closegraph();
}

Program for sound


# include "stdio.h"
# include "dos.h"
# include "conio.h"
void main()
{
int i,j;
clrscr();
printf("\t\t\t pl. wait..");
for(j=0;j<10;j++)
for(i=500;i<3000;i= i + 50)
{
sound(i);
delay(5);
nosound(); // to stop the current frequency
}
}

Program for displaying home


# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd,gm;
gm=0;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");

cleardevice();
line(200,200,200,300);
moveto(200,300);
lineto(400,300);
lineto(400,200);
lineto(200,200);
lineto(300,100);
lineto(400,200);
moveto(220,200);
rectangle(220,225,270,300);
moveto(300,200);
rectangle(320,220,350,250);
moveto(330,220);

77
QUALITY COMPUTER EDUCATION

lineto(330,250);
moveto(340,220);
lineto(340,250);
gotoxy(33,11);
printf("Happy Home");
getch();
}

program to move a ball from left to right


# include "stdio.h"
# include "conio.h"
# include "graphics.h"

void main()
{
int gd,gm,i;
int a[100][100];
gd=gm=0;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
setcolor(YELLOW);
setbkcolor(BLUE);
setfillstyle(1,YELLOW);
pieslice(400,100,0,360,30);
getimage(360,60,440,140,a);
cleardevice();
putimage(1,300,a,0);

for(i=1;i<640;i+=2)
{
putimage(i,300,a,0);
putimage(i+2,300,a,0);
}
getch();
closegraph();
cleardevice();
}

78
QUALITY COMPUTER EDUCATION

STACKS
stack : it is called linear data structure . in which data is inserting and deletion will done
from same end called top of the stack. it's style is called last in first out(LIFO)).

Program for stack implementation (insert,delete, display)


int m[10],top=-1;
#define n 5
void insert();
void display();
void delete();
main()
{

int choice;
clrscr();
do
{
clrscr();
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4.Exit\n");
printf("Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1: insert();getch();break;
case 2: delete();getch();break;
case 3: display();getch();break;
default: printf("Exiting from the program");
}
}while(choice!=4);
getch();
}
void insert()
{
int x;
if(top==n-1)
{
printf("Stack is full");
}
else
{
printf("Enter element :");
scanf("%d",&x);

79
QUALITY COMPUTER EDUCATION

top++;
m[top]=x;
}
}
void display()
{
int i;
if(top==-1)
{
printf("No values to display");
}
else
{
for(i=0;i<=top;i++)
{
printf("m[%d] is %4d\n",i,m[i]);
}
}
}
void delete()
{
int x;
if(top==-1)
{

printf("Stack is empty");
}
else
{
x=m[top--];
printf("Deleted element is :%d",x);
}
}

program for stack operation (accepting elements)


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
int top,n,i;
char ch;
int a[100],ele;
clrscr();
top=-1;
printf("enter n value");

80
QUALITY COMPUTER EDUCATION

scanf("%d",&n);
printf("enter elements into array");
scanf("%d",&a[i]);
printf("do u want to push");
scanf("%c",&ch);
if(top==n)
{
puts("stack is full");
exit(1);
}
else
{
top++;
a[top]=ele;
getch();
}
}

program for stack operation (push,pop-pointer to structures)


#include<stdio.h>
#define max 5
#include<conio.h>
typedef struct
{
int top;
int arr[max];
}s;
void main()
{
int choice,x;
s stack;
void create(s*);
int isempty(s*);
int isfull(s*);
void push(s*,int);
int pop(s*);
creat(&stack);
do
{
clrscr();
printf("\n MENU::\n");
puts(" ");
printf("1.PUSH\n");
printf("2.POP\n");
printf("3.EXIT\n");
printf("enter your choice");

81
QUALITY COMPUTER EDUCATION

scanf("%d",&choice);
switch(choice)
{
case 1:clrscr();
if(isfull(&stack))
{
printf("stack full,press any key to continue");
getch();
}
else
{
printf("enter value");
scanf("%d",&x);
push(& stack,x);
}
break;
case 2:clrscr(); if(isempty(&stack))
{
printf("stack empty,press any key to continue");
getch();
}
else
{
printf("value popped is %d\n",pop(&stack));
printf("press any key to continue");
getch();
}
}
}
while(choice!=3);
}
void create(s *v)
{
v->top=-1;
}
int isempty(s *v)
{
if(v->top==-1)
return 1;
else
return 0;
}
int isfull(s *v)
{
if(v->top==max-1)
return 1;

82
QUALITY COMPUTER EDUCATION

else
return 0;
}
void push(s *v,int value)
{
v->arr[++v->top]=value;
}
int pop(s *v)
{
return(v->arr[v->top--]);
}

program for stack implementation (students)


#include<stdio.h>
struct student
{
int sno;
char sname[30];
struct student *next;
};
struct student *rec,*top=NULL;
main()
{
char ch;
do
{
clrscr();
printf("Main Menu\n");
printf("1.Add Records\n");
printf("2.List Records\n");
printf("3.Exit\n");
printf("Enter Choice[1-3]:");
ch=getchar();fflush(stdin);
if(ch=='1') add();
else if(ch=='2') list();
else if(ch=='3') exit(0);
else {printf("\nInvalid Option");getch();}
}while(ch!='3');
}

add()
{
clrscr();
rec=(struct student*) malloc(sizeof(struct student));
printf("Enter Sno:");scanf("%d",&rec->sno);fflush(stdin);
printf("Enter SName:");gets(rec->sname);

83
QUALITY COMPUTER EDUCATION

if(top==NULL)
{top=rec;rec->next=NULL;}
else
{rec->next=top;top=rec;}
}

list()
{
struct student *ptr;
clrscr();
ptr=top;
while(ptr!=NULL)
{
printf("%3d %-30s\n",ptr->sno,ptr->sname);
ptr=ptr->next;
}
getch();
}

84
QUALITY COMPUTER EDUCATION

QUEUES
queue : it is called linear data structure . in which value is inserting
at from one end is called rear and value is deleted at from another end is
called front. in which first inserted element will be deleted first. it is
called first in first out FIFO)

and deletion will done from same end called top of the stack. it's style
is called last in first out(LIFO)).

Program for implementation of queue (insert,delete, display)


int m[10],front =0,rear=-1;
#define n 5
void insert();
void display();
void delete();
main()
{

int choice;
clrscr();
do
{
clrscr();
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4.Exit\n");
printf("Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1: insert();getch();break;
case 2: delete();getch();break;
case 3: display();getch();break;
default: printf("Exiting from the program");
}
}while(choice!=4);
getch();
}
void insert()
{
int x;
if(top==n-1)
{
printf("Queue is full");
}

85
QUALITY COMPUTER EDUCATION

else
{
printf("Enter element :");
scanf("%d",&x);
rear++;
m[rear]=x;
}
}
void display()
{
int i;
if(front <=rear)
{
for(i=front;i<=rear;i++)
{

printf("m[%d] is %4d\n",i,m[i]);
}
}
else
{
printf("Queue is empty");
}
}

void delete()
{
int x;
if(front <=rear)
{

x=m[front];
front++;

printf("Deleted element is :%d",x);


}
else
{
printf("Queue is empty");
}
}

Program for implementation of queue (student)


#include<stdio.h>
struct student
{

86
QUALITY COMPUTER EDUCATION

int sno;
char sname[30];
struct student *next;
};
struct student *rec,*top=NULL,*ptr;
main()
{
char ch;
do
{
clrscr();
printf("Main Menu\n");
printf("1.Add Records\n");
printf("2.List Records\n");
printf("3.Exit\n");
printf("Enter Choice[1-3]:");
ch=getchar();fflush(stdin);
if(ch=='1') add();
else if(ch=='2') list();
else if(ch=='3') exit(0);
else {printf("\nInvalid Option");getch();}
}while(ch!='3');
}

add()
{
clrscr();
rec=(struct student*) malloc(sizeof(struct student));
printf("Enter Sno:");scanf("%d",&rec->sno);fflush(stdin);
printf("Enter SName:");gets(rec->sname);

if(top==NULL)
{top=rec;rec->next=NULL;ptr=top;}
else
{ptr->next=rec;rec->next=NULL;ptr=rec;}
}

list()
{
struct student *rptr;
clrscr();
rptr=top;
while(rptr!=NULL)
{
printf("%3d %-30s\n",rptr->sno,rptr->sname);

87
QUALITY COMPUTER EDUCATION

rptr=rptr->next;
}
getch();
}

88
QUALITY COMPUTER EDUCATION

TREES

A tree is a finite set of one or more nodes such that (i) there is a specially designed node
called root (ii)the remaining nodes are partitioned into n>= 0 disjoint sets T1,
T2,T3,.....Tn where each of these sets is a tree.

C
B D

E F G H I J

K L
M

There are many terms, which are often used when referring to trees.

A Node stands for the item of information plus the branches to other items. Consider the
above figure. This tree has 13 nodes. The root node is A. Normally we draw root node
always at top.

The no of sub trees of a node is called a degree. The degree of node A is 3, of C is 1 and
of F is zero.

The nodes that of have degree zero are called leaf nodes. The above fig K, L, F, G, M, I, J
are leaf nodes (we also call them as terminal nodes..). Alternatively the other nodes are
non-terminal nodes.

The degree of a tree is the maximum degree of its individual trees. Thus the degree of
above tree is 3.

The level of tree is defined by initially letting the root node one. If a node is at level l
then its children are at level l+1.The figure shows the levels of different nodes in a tree.

The height and depth of a tree is defined to be the maximum level of its subnodes.

89
QUALITY COMPUTER EDUCATION

A forest is a set of n>= 0 disjoint trees. The notion of a forest is very close to that of a
tree because if we remove a root of a tree we get a forest. For example in the above tree if
we remove A we get a forest of three trees.

The other ways to draw a tree is by list


Ex: (A(B(E(K,L),F),C(G),D(H(M),I,J)))

Binary TREES

A binary tree is an important type of tree structure, which occurs very often it is
characterized by the fact that any node can have at most two branches.

Definition: A binary tree is a finite set of nodes which is either empty or consists of a root
and distinct binary trees called left subtree and right subtree

The distinctions between a binary tree and a tree should be analyzed. First of all there is
no tree having zero nodes, but there is an empty binary tree
The two binary trees drawn below are different .

A A

B B

The first has right subtree empty and the second has left sub tree empty. If we treat the
above trees as a tree the there is absolutely no difference between them.
LEVEL
A A 1

B B C 2

C D E F G 3

D
H I 4

5
E

90
QUALITY COMPUTER EDUCATION

Above fig shows two simple binary trees. These two trees are special kids of
binary trees. The first is a skewed tree, skewed to the left. The other fig is a complete
binary tree. Notice that all terminal nodes are adjacent levels. The terms that we introduce
for trees such as: degree, level, height, leaf, parent, child all apply to binary trees in
natural way. Before representations for binary tree let us first make some relevant
observations regarding such trees.

First What is the maximum no of nodes in a binary tree of depth k?

i. The maximum no nodes on lovel m of a binary tree is 2m-1, m>= 1.


ii. The maximum no of nodes in a binary tree of depth k is 2k – 1

For any non empty binary tree T if n0 is the no of trminal nodes and n2 the no of nodes of
degree 2 then n0 = n2 +1

A C program that illustrates the concept of btree :

#include <iostream.h>
#include <stdio.h>
#include <malloc.h>
#include <conio.h>

struct Node
{
int info;
struct Node* left;
struct Node *right;
}*root,*p,*q;

Node * set_right(Node * p,int n);


Node * set_left(Node * p,int k);
void inord_trav(Node *p);
void preord_trav(Node *p);
void postord_trav(Node *p);

void main()
{
clrscr();
char ch;

root = (Node *) malloc (sizeof(Node)); // Creating a root node


cout <<"\n Enter root data here : ";
cin >> root->info;
root->left = NULL;
root->right = NULL;

91
QUALITY COMPUTER EDUCATION

cout <<"\n Do u wish to add no in tree ";


ch = getche();

while(ch != 'n') // inserting a new node in tree


{
int n;
fflush(stdin);
cout<< "\n Enter a number here : ";
cin >> n;

p= root;
q = root;

while((n!=p->info) && (q!=NULL))


{
p=q;
if(n <p->info)
q = p->left;
else
q = p->right;
}
if(n ==p->info)
cout << "\n Duplicate ...";
else
{
if(n <p->info)
p = set_left(p,n);
else
p= set_right(p,n);
}

cout <<"\n Do u wish to add no in tree ";


ch = getche();
}
cout <<"\n Inorder Traversal ..: ";
inord_trav(root);
getch();
cout <<"\n Postorder Traversal ..: ";
postord_trav(root);
getch();
cout<<"\nPreorder Travesal ...: ";
preord_trav(root);

getch();
}

92
QUALITY COMPUTER EDUCATION

Node *set_left(Node *r , int n1)


{
Node *temp;
if(r->left != NULL)
cout << "\n Illegal Operation ....";
else
{
temp = (Node *) malloc (sizeof(Node));
fflush(stdin);
temp->info = n1;
temp->left = NULL;
temp->right = NULL;

r->left = temp;
}
return r;
}

Node *set_right(Node *r , int n1)


{
Node *temp;
if(r->right != NULL)
cout << "\n Illegal Operation ....";
else
{
temp = (Node *) malloc (sizeof(Node));
fflush(stdin);
temp->info = n1;
temp->left = NULL;
temp->right = NULL;

r->right = temp;
}
return r;
}

void inord_trav(Node *p)


{
if(p!= NULL)
{
inord_trav(p->left);
cout <<p->info<<"\t";
inord_trav(p->right);
}
}

93
QUALITY COMPUTER EDUCATION

void preord_trav(Node *p)


{
if(p!= NULL)
{
cout <<p->info<<"\t";
preord_trav(p->left);
preord_trav(p->right);
}
}

void postord_trav(Node *p)


{
if(p!= NULL)
{
postord_trav(p->left);
postord_trav(p->right);
cout <<p->info<<"\t";
}
}

A C program that illustrates the concept of btree :

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

struct node
{
int no;
struct node *left;
struct node *right;
};

void printtreeinorder(struct node *);


void printtreepreorder(struct node *);
void printtreepostorder(struct node *);

struct node *build(struct node *,int);

void main()
{
struct node *root;
char ch;
int tno=0;
clrscr();

94
QUALITY COMPUTER EDUCATION

root=NULL;
printf("\nEnter any number: ");
scanf("%d",&tno);
fflush(stdin);

while(tno != 0)
{

root = build(root,tno);

printf("\nEnter any number (0-stop)");


scanf("%d",&tno);
fflush(stdin);
}

printf("\n\nPrinttree Inorder : ");


printtreeinorder(root);
printf("\n\nPrinttree Preorder : ");
printtreepreorder(root);
printf("\n\nPrinttree Postorder: ");
printtreepostorder(root);
getch();
}

struct node *build(struct node *bnode , int tno)


{
if(bnode == NULL)
{
bnode =(struct node *) malloc(sizeof(struct node));
bnode->no = tno;
bnode->left = bnode->right = NULL;
}
else if(tno < bnode->no)
bnode->left = build(bnode->left,tno);
else
bnode->right = build(bnode->right,tno);
return (bnode);
}

void printtreeinorder(struct node *ptr)


{
if(ptr != NULL)
{

95
QUALITY COMPUTER EDUCATION

printtreeinorder(ptr->left);
printf("\t%d",ptr->no);
printtreeinorder(ptr->right);
}
}

void printtreepreorder(struct node *ptr)


{
if(ptr != NULL)
{
printf("\t%d",ptr->no);
printtreepreorder(ptr->left);
printtreepreorder(ptr->right);
}
}

void printtreepostorder(struct node *ptr)


{
if(ptr != NULL)
{
printtreepostorder(ptr->left);
printtreepostorder(ptr->right);
printf("\t%d",ptr->no);
}

program for binary tree

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

struct node
{
int no;
struct node *left;
struct node *right;
};

void printtree1(struct node *);


void printtree2(struct node *);
void printtree3(struct node *);

96
QUALITY COMPUTER EDUCATION

struct node *build(struct node *,int);

void main()
{
struct node *root,*build();
char ch;
int tno=0;
clrscr();
root=NULL;
printf("\nEnter any number: ");
scanf("%d",&tno);
fflush(stdin);
while(tno != 0)
{
root = build(root,tno);
printf("\nEnter any number (0-stop)");
scanf("%d",&tno);
fflush(stdin);
}

printtree1(root);
printf("\n");
printtree2(root);
printf("\n");
printtree3(root);

getch();
}

struct node *build(struct node *bnode , int tno)


{
if(bnode == NULL)
{
bnode =(struct node *) malloc(sizeof(struct node));
bnode->no = tno;
bnode->left = bnode->right = NULL;
}
else if(tno < bnode->no)
bnode->left = build(bnode->left,tno);
else
bnode->right = build(bnode->right,tno);
return (bnode);
}

//inorder

97
QUALITY COMPUTER EDUCATION

void printtree1(struct node *ptr)


{
if(ptr != NULL)
{
printtree1(ptr->left);
printf("%d\t",ptr->no);
printtree1(ptr->right);
}
}

//preorder

void printtree2(struct node *ptr)


{
if(ptr != NULL)
{
printf("%d\t",ptr->no);
printtree2(ptr->left);
printtree2(ptr->right);
}
}

//postorder

void printtree3(struct node *ptr)


{
if(ptr != NULL)
{
printtree3(ptr->left);
printtree3(ptr->right);
printf("%d\t",ptr->no);
}
}

98

Das könnte Ihnen auch gefallen