You are on page 1of 229

# C Programs By VINOD

/* C program to find the area of a circle, given it’s radius */

#include<stdio.h>

#define PI 3.1416

void main()

{

float r, area;

clrsce();

printf("\n\n enter the radius of circle\n");

scanf("%f", &r);

area = PI * r * r;

printf("\n The area of the circle = %f\n", area);

getch();

}

/* C program to find the area of a triangle, given 3 sides */

#include<stdio.h>

1

C Programs By VINOD

#include<math.h>

void main()

{

float a, b, c, s, area;

clrsce();

printf("\n\n enter the values of 3 sides of a triangle\n\n\n");

scanf("%f%f%f", &a, &b, &c);

s=(a+b+c)/2;

area = sqrt(s * (s-a) * (s-b) * (s-c));

printf("\n The area of the triangle = %f\n", area);

getch();

}

Progra to find Gross Salary

#include<stdio.h>

2

C Programs By VINOD

#include<conio.h>

void main()

{

int gs,bs,da,ta;

clrscr();

printf("enter basic salary: ");

scanf("%d",&bs);

=(10*bs)/100;

ta=(12*bs)/100;

gs=bs+da+ta;

printf("gross salary=%d",gs);

getch();

}

Program to find factorial of a number.

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i,fact=1;

clrscr();

3

C Programs By VINOD

printf("Enter any no: ");

scanf("%d",&n);

for(i=n;i>=1;i--)

{

fact=fact*i;

}

printf("Factorial=%d",fact);

getch();

}

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i,sum=0;

clrscr();

printf("Enter any no: ");

scanf("%d",&n);

for(i=2;i<=n-1;i++)

printf(" 1/%d +",i);

for(i=1;i<=n;i++)

4

} /* true. printf("The value of 2<1 is %d\n".It prints out the first N Fibonacci numbers. (1<2)). (2<1)).n).C Programs By VINOD sum=sum+i.h> int main(void) { printf("The value of 1<2 is %d\n". */ #include <stdio. getch().h> 5 .sum+1/n).c -.What are in C the values of TRUE and FALSE? */ #include <stdio. printf(" 1/%d".c -. } /* fibo. printf("\nSum=1/%d".

C Programs By VINOD int main(void) { int n. i. /* The value of the (i+1)th fibonacci number */ int twoaway. } } } 6 . /* The index of fibonacci number to be printed next */ int current. /* The value of the (i+2)th fibonacci number */ printf("How many Fibonacci numbers do you want to compute? "). /* The value of the (i)th fibonacci number */ int next. twoaway = current+next. &n). i++) { printf("\t%d \t %d\n". i<=n. current). for (i=1. else { printf("\n\n\tI \t Fibonacci(I) \n\t=====================\n"). /* The number of fibonacci numbers we will print */ int i. scanf("%d". next = twoaway.\n"). if (n<=0) printf("The number should be positive. current = next. next = current = 1.

h> int main() 7 .C Programs By VINOD /* The output from a run of this program was: How many Fibonacci numbers do you want to compute? 9 I Fibonacci(I) ===================== 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21 9 34 */ A simple example showing some comparison operators #include <stdio.

scanf("%d". kilobytes. /*convert kilobytes to megabytes*/ 8 .&megabytes).&number2).C Programs By VINOD { int number1 . printf("Please enter the amount of megabytes to convert. number1 < number2). printf("Enter the number2 number to compare. printf("number1 > number2 has the value %d\n". printf("number1 < number2 has the value %d\n".\n"). /*convert megabytes to kilobytes*/ kilobytes = megabytes * 1024. number2.\n"). printf("number1 == number2 has the value %d\n". printf("Enter the number1 number to compare. scanf("%d".&number1). number1 > number2). number1 == number2).h> int main(void) { double megabytes . scanf("%Lf".\n"). } Convert MB to KB #include <stdio. return 0.

C Programs By VINOD /*this is for kilobytes to megabytes*/ /*megabytes = kilobytes / 1024*/ printf("There are %Lf kilobytes in %Lf megabytes.i.h> #include<stdlib.kilobytes.year.m. return 0. for(i=1.&d.i++) { printf("Enter the date : ").&m.h> #include<conio. int d.month. scanf("%d".megabytes). scanf("%d%d%d".&n).day. printf("Enter how many times you want to run this program : "). } Program to find your Day of Birth given Date of Birth #include<stdio.&y).y.n. 9 .i<=n.\n".h> main() { clrscr().

case 2: case 3: case 11: month = 4. year = year/4. exit(0). year = year+y-1900. getch(). switch(m) { case 1: case 10: month = 1. break. 10 . break. } year = y-1900. case 7: case 4: month = 0.C Programs By VINOD if( d>31 || m>12 || (y<1900 || y>=2000) ) { printf("INVALID INPUT").

case 5: month = 2. case 6: month = 5.C Programs By VINOD break. case 9: case 12: month = 6. break. case 8: month = 3. switch(day) { case 0: printf("Day is SATURDAY"). break. 11 . break. year = year+d. break. } year = year+month. break. day = year%7.

C Programs By VINOD case 1: printf("Day is SUNDAY"). break. break. break. return 0. break. case 5: printf("Day is THURSDAY"). } 12 . } } getch(). case 2: printf("Day is MONDAY"). break. case 6: printf("Day is FRIDAY"). break. case 3: printf("Day is TUESDAY"). case 4: printf("Day is WEDNESDAY").

d.&e). scanf("%d".h> main() { int a. clrscr(). } if (e>3000) printf("Invalid").C Programs By VINOD Program for Decimal to Roman Number conversion #include<stdio. 13 .&e). printf ("Enter the number again:").c. c = ((e/10)%10)*10.b. d = ((e/1)%10)*1. printf("Input a number (between 1-3000):"). b = ((e/100)%10)*100. scanf ("%d". a = (e/1000)*1000. while (e==0||e>3000) { printf ("ERROR: Invalid Input!").e.

else if (a ==2000) printf("MM"). else if (b ==500) printf("D"). else if (b == 600) printf("DC"). else if (b == 400) printf("CD").C Programs By VINOD if (a ==1000) printf("M"). else if (b == 300) printf("CCC"). else if (b == 700) printf("DCC"). if (b == 100) printf("C"). else if (a ==3000) printf("MMM"). else if (b ==800) 14 . else if (b == 200) printf("CC").

else if (c == 40) printf("XL"). if (c == 10) printf("X"). else if (c == 60) printf("LX"). else if (c == 20) printf("XX"). else if (b == 900) printf("CM"). else if (c == 30) printf("XXX"). else if (c == 90) printf("XC"). 15 . else if (c ==80) printf("LXXX"). else if (c == 70) printf("LXX").C Programs By VINOD printf("DCCC"). else if (c ==50) printf("L").

else if (d == 7) printf("VII").C Programs By VINOD if (d == 1) printf("I"). getch(). else if (d == 6) printf("VI"). else if (d == 2) printf("II"). else if (d == 9) printf("IX"). else if (d == 3) printf("III"). } Factorial series-e^x 16 . else if (d == 4) printf("IV"). else if (d ==5) printf("V"). else if (d ==8) printf("VIII").

1+s).&x). printf("You have this series:-1+x/1! + x^2/2! + x^3/3! + x^4/4!. getch(). fflush(stdin).r.h> #include<math. } 17 . } printf("The sum of %d terms is %f".h> long int factorial(int n).i++) { s=s+((float)pow(x. void main() { int x. scanf("%d".h> #include <conio.x^x/x!").i.i<=x.. char c. s=0.x.C Programs By VINOD #include <stdio. clrscr(). for (i=1.i)/(float)factorial(i)). printf("To which term you want its sum? "). float s.

00001.p.h> main() { float a. return(n). } Square Root of a number by using simple calculations #include<stdio. do { printf(" PROGRAM TO FIND SQUARE ROOT OF A NUMBER").k. 18 . printf("ENTER A NUMBER(-1 to Quit) :"). else n=n*factorial(n-1).b.C Programs By VINOD long int factorial(int n) { if (n<=1) return(1). scanf("%f".e=0. clrscr().&k).h> #include<conio.

while(p-k>=e) { b=(a+(k/a))/2. }while(k!=-1). } Volumes & Areas /PROGRAM TO CALCULATE AREA.VOLUME. clrscr(). getch(). getch().h> 19 . p=a*a.PERIMETER OF A PARTICULAR GEOMETRIC SHAPE/ #include<stdio. } printf("SQUARE ROOT IS = %f".a). p=a*a. a=b.C Programs By VINOD a=k.

getch().14159 char ch. intro(). main() { clrscr(). 20 .h> #include<math. clrscr(). square(). do { ch=menu().C Programs By VINOD #include<conio. switch(ch) { case 'a': case 'A': clrscr().h> #define PI 3.

rect(). case 'd': case 'D': clrscr().C Programs By VINOD getch(). case 'b': case 'B': clrscr(). case 'e': case 'E': clrscr(). case 'c': case 'C': clrscr(). break. circl(). break. getch(). tri(). getch(). break. break. getch(). 21 .

qua(). case 'g': case 'G': clrscr(). getch(). case 'f': case 'F': clrscr(). tra(). break. break. case 'h': case 'H': clrscr(). getch(). case 'i': 22 . para(). getch().C Programs By VINOD rom(). getch(). break. break.

msector(). break. semicir(). getch(). break.C Programs By VINOD case 'I': clrscr(). case 'l': case 'L': clrscr(). cone(). getch(). getch(). sphere(). 23 . break. getch(). case 'j': case 'J': clrscr(). case 'k': case 'K': clrscr().

cuboid(). break. break. getch(). getch(). case 'm': case 'M': clrscr(). case 'p': case 'P': clrscr(). case 'o': case 'O': clrscr(). break. 24 .C Programs By VINOD break. case 'n': case 'N': clrscr(). cyll(). getch(). cube().

25 . case 'q': case 'Q': exit(1). getch(). CIRCUMFERENCES "). cprintf("####################################################################### #########"). textcolor(4). clrscr(). printf("PROGRAM TO CALCULATE AREAS . break. getch().C Programs By VINOD hemisphe(). } intro() { int i. VOLUMES . printf(""). } } while(ch!='Q'||ch!='q'). textcolor(2).

SQUARE B.CIRCLE 26 . ----------------------- A.C Programs By VINOD printf("====================================================="). cprintf("################################################################# ###############"). textcolor(2). getch(). printf(" MENU Two Dimensional Shapes. } menu() { clrscr(). textcolor(7). printf("==========================="). printf("OF VARIOUS GEOMETRIC SHAPES").RECTANGLE C.

printf(" Three Dimensional Shapes.CUBOID P.QUADRILATERAL. I.SPHERE L.HEMISPHERE 27 .TRAPEZIUM H.PARALLELOGRAM G.SEMICERCLE J.TRIANGLE E.CONE M.CYLLINDER N.CUBE O. ------------------------- K.C Programs By VINOD D.SECTOR ").RHOMBUS F.

scanf("%c".&ch).a.C Programs By VINOD Q.QUIT Enter Your Choice :").a). return(ch). printf(" Perimeter of square : %.p.i++) { 28 . for(i=1.int i. printf("Square is .3f units".j.3f sq. printf(" Enter side of square:"). scanf("%f".p). a=s*s.&s)."). p=4*s. } /***** SUB FUNCTIONS *****/ /***** 2 D SHAPES *****/ square() { float s.units"..i<=s. printf(" Area of square : %..

printf("Enter length and breadth of rectangle:Length:"). int i.a).. 29 . scanf("%f".3f units". printf("Breadth:").&l). } rect() { float a. printf("Rectangle is.l.p. printf(" Perimeter of rectangle : %.j++) cprintf("ÛÛ"). scanf("%f". a=l*b. p=2*(l+b).units". for(i=1. } return(0).j<=s.C Programs By VINOD textcolor(10).i<=b.i++) { textcolor(4).b.3f sq.. printf(" ").&b).j."). printf("Area of rectangle : %.p). for(j=1.

p).&c).&s). printf("Perimeter of triangle : %. s=p/2.c. area=sqrt(s*(s-a)*(s-b)*(s-c)). float a.p. printf("Enter three sides of triangle:").a. p=a+b+c. } return(0).s. } rom() { float s.3f sq. } tri() { float area. 30 .j++) cprintf("ÛÛ"). scanf("%f".j<=l. scanf( "%f%f%f".C Programs By VINOD for(j=1.p.&a.3f units". printf("Enter side and diagonals of a rhombus:Side:").units".d1.b. printf(“Area of a triangle : %. printf("").&b.d2.area).

printf("Enter height.scanf("%f". printf("Enter radius of circle:").units". a=PI * r * r. a=0.&h).5*d1*d2. } para() { float a. p=2 * PI * r. scanf("%f". printf("Area of rhombus :%. printf("Perimeter of rhombus :%.C Programs By VINOD printf("Diagonal :").&r). printf("Area of circle : %. scanf("%f".base.3f sq.&d2).h.p.l.3f units". printf("Base or Length :").a). p=4*s.a.p.length. printf("Circumference of circle : %.breadth of parallalogram :" ). printf("Height :").units".&l). scanf("%f".scanf("%f".a).p). 31 .3f units". printf("Diagonal :").p). } circl() { float r.3f sq.&d1).b.

base=l. } tra() { float a.3f sq. are=0.C Programs By VINOD printf("Breadth :").&b). printf("Area of parallogram :%. 32 .3f units".units".&a).d. p=2 * ( l + b ).d.a). printf("Perimeter of parallalogram :%.units". a=base*h.area.&d).&b). printf("Side:"). printf("Area of trapezium : %. } qua() { float a.b. scanf("%f". scanf("%f". scanf("%f". printf("Side:").5 * d * (a+b).p).3f sq. printf("Enter height and lengths of two parallel sides:Height :"). scanf("%f".are.are).b.

p. p= (PI * r ) + (2 * r). scanf("%f".&d).&r). } semicir() { float a.&b).5* PI * r * r. printf("Radius :").p). } msector() { float x.5 * d * (a + b). printf("Area of quadrilateral : %. printf("Distance :"). printf("Diagonal :"). printf("Distance :"). scanf("%f".r. area). printf("Enter radius and angle of sector:").3f sq. area= 0.r.scanf("%f".p.units".3f sq. a=0.units".C Programs By VINOD printf("Enter diagonal and perpendicular distances from opposite vertices:").3f units".a. 33 .&a). printf("Enter radius of semicircle:"). printf(“Circumference of semicircle : %.a). printf("Area of semicircle : %.temp. scanf("%f".

r.p).v.0/3. printf("Enter radius of sphere :").3f units".units".&r).3f sq.a).tsa). } /******** 3 DIMENSIONAL SHAPES *********/ sphere() { float lsa. printf("Volume of sphere :%. temp= x/360. printf("Total surface area of sphere :%.units".C Programs By VINOD scanf("%f".units". v=(4. p= temp * (2 * PI * r). printf("Circumference of sector : %.&r). a= temp * (PI * r * r).tsa. printf("Area of sector : %.v).0)*PI*r*r*r.&x). printf("Angle(in degrees) :").3f cu. } cone() 34 . tsa=4*PI*r*r. scanf("%f".3f sq. scanf("%f".

tsa). printf("Total surface area of cone :%.r.s .&h).3f sq. } cyll() { float lsa. printf("Height :").3f cu. slant height of cone :"). lsa=2*PI*r*h. scanf("%f".units".lsa.lsa).&r).&h).tsa.&r).3f sq.units". v=PI*r*r*h. v=(PI * r * r * h)/3. lsa=PI * r * s. printf("Height :"). 35 .&s). printf("Slant height :").v.tsa. scanf("%f".C Programs By VINOD { float h.tsa).3f sq. printf("Volume of cone :%. printf("Enter height and radius of cyllinder"). scanf("%f". printf("Total surface area of cyllinder :%. printf("Radius :"). tsa=PI * r *(s+r). printf("Radius :"). scanf("%f".units".h.height. printf("Enter base radius .v). scanf("%f". printf("Lateral surface area of cone :%.v. tsa=2*PI*r*(h+r).units".r.

d. v= s * s * s.b. printf("Length :").d. printf("Enter length. printf("Diagonal of cube :%. printf("Lateral surface area of cube :%.lsa).breadth.tsa).&s).units".3f sq.v.d).units". } cube() { float lsa.tsa. scanf("%f".h.&l). printf("Volume of cube :%. scanf("%f".&b).C Programs By VINOD printf("Curved surface area of cyllinder :%.tsa.units". printf("Breadth :").v. 36 .units".lsa).3f sq. printf("Enter side of cube :").3f sq.l. printf("Total surface area of cube :%. lsa=4 * s * s. tsa=6 * s * s. } cuboid() { float lsa.3f cu. scanf("%f".3f cu.3f units".s.units".height of cuboid :"). d=s*sqrt(3).v). printf("Volume of cyllinder :%.v).

printf("Total surface area of hemisphere :%. v=(2. printf("Total surface area of cuboid :%.units".tsa). printf("Volume of hemisphere :%.3f sq. v=l*b*h.r.3f cu.3f sq.units". printf("Diagonal of cuboid :%. } hemisphe() { float lsa. } 37 .C Programs By VINOD printf("Height :"). printf("Enter radius of hemisphere :"). tsa=3*PI*r*r. printf("Volume of cuboid :%.3f cu.tsa).0)*PI*r*r*r. tsa = lsa + 2 * l * b.units".units". scanf("%f".0/3. lsa =2 * h *( l+b ). printf("Lateral surface area of hemisphere :%.3f units".v).tsa.units".&r).3f sq.&h).3f sq.lsa). d=sqrt(l*l + b*b + h*h ).v).lsa).d). lsa=2*PI*r*r. printf("Lateral surface area of cuboid :%.units".v. scanf("%f".

clrscr().h> void main() { int a. getch(). if(-5) printf("This Works\n"). if(a=10) printf("This Works\n"). if(3+2%5) printf("This Works\n").C Programs By VINOD /*simple program for “if statement”*/ #include<stdio. } /* program to find a number is positive or negative*/ #include<stdio.h> void main() 38 .

scanf("%d". else printf("%d is negative\n"). &a). scanf("%d". } /*program to find a number is even or odd*/ #include<stdio.. if(a >=0) printf("%d is positive\n").h> void main() { int a.C Programs By VINOD { int a. clrscr(). printf("Enter a Number. clrscr(). &a). getch()..\n"). printf("Enter a Number.\n"). 39 .

getch(). clrscr(). else printf("%d is odd\n"). printf("enter your total average. } /* program to find grade of a student*/ #include<stdio. &avg).h> void main() { float avg. scanf("%f".C Programs By VINOD if(a%2 == 0) printf("%d is even\n").. 40 .\n").

99) printf("Third Class\n").h> void main() { int a.b. else if(avg>=50. else printf("You Fail\n"). 41 .0 && avg<=40.99) printf("Second Class\n").99) printf("First Class\n"). getch(). else if(avg>=35. else if(avg>=60.0 && avg<=59.0 && avg<=84.C Programs By VINOD if(avg>=85.c. } /* program to find largest of 3 numbers */ #include<stdio.0) printf("Distinction\n").

} else { if(b > c) printf("%d\n". printf("Enter 3 Numbers.c). if(a > b) { if(a > c) printf("%d\n". printf("The Largest Number Is = ").c).\n").C Programs By VINOD clrscr().&c). a). scanf("%d%d%d". &a. else printf("%d\n". b).&b.. else printf("%d\n". } 42 .

c2=0. void main() { int c1=0.c3=0.c4=0.h> #define NULL 0 FILE *fpt.name[20].can/'t open file %s"."r").name). clrscr(). else { while ((c=getc(fpt))!=EOF) { 43 . char c.h> # include <conio.C Programs By VINOD getch(). } /*Prg. if (fpt==NULL) printf("ERROR .c5=0. to correct rudimentary syntax errors*/ #include <stdio.").z. fpt=fopen(name. printf("Enter the name of file to be checked :. gets(name).

if (c=='[') c2=c2+1. if ((int)c==39) { if (c1!=0) { 44 . if (c==')') c1=c1-1. if (c==']') c2=c2-1.C Programs By VINOD if (c=='(') c1=c1+1.Unbalanced parenthesis ()").Unbalanced brackets []"). if (c2!=0) printf("ERROR . if (c=='}') c3=c3-1. } if (c=='{') c3=c3+1. if (c=='') { if (c1!=0) printf("ERROR .

} } 45 . printf("ERROR . } else { z=(char)34. } if ((int)c==34) { if (c1!=0) { if (c5==0) c5=c5+1. else c5=c5-1. else c4=c4-1.Unbalanced %c ". } else printf("ERROR .Unbalanced ' ").C Programs By VINOD if (c4==0) c4=c4+1.z).

Unbalanced ' ").Unbalanced ' ").no. if (c1==0 && c2==0 && c3==0 && c4==0 && c5==0) printf("Program is up to date. if (c5!=0) printf("ERROR . if (c2!=0) printf("ERROR .Unbalanced braces {}").C Programs By VINOD } } if (c1!=0) printf("ERROR . fclose(fpt).no. of blanks. to count no. if (c3!=0) printf("ERROR .Unbalanced brackets []"). of characters. if (c4!=0) printf("ERROR . getch(). of lines in a multi line string*/ 46 .Unbalanced parenthesis ()"). WELL DONE!"). of words & no. } /*Prg.

nw=1.nb=0.C Programs By VINOD #include <stdio.h> void main() { char c. printf("STRING:.&choice). clrscr().count.h> #include <conio. while ((c=getchar())!=EOF) { switch(1) { case 1: if (c==EOF||c==' '||c=='') . printf("ENTER STRING:. scanf("%c".nl=1.i/*. 47 . else nc=nc+1.").choice.")."). int nc=0. printf("String will be terminated when you press Ctrl-Z.flag=1*/.

} if (c!=' ') { nc=nc+1. nb=nb+1. 48 . while((c=getchar())==' ') { nb=nb+1.C Programs By VINOD case 2: if (c==' ') { nc=nc+1. nw=nw+1. nc=nc+1. } } case 3: if(c=='') { nc=nc+1.

printf("no. printf("no. nw=nw+1. void main() 49 . scanf("%c". to sort any no.*/ void sort(void). of lines is %d". } } } printf("no. nl=nl+1. of words is %d".nb). } /*Prg.C Programs By VINOD nb=nb+1. fflush(stdin). of characters is %d". int c. of blanks is %d".l. printf ("Do you want to continue?(y/n):.&choice).nl). of numeral i-p in ascending or descending order. printf("no.").nw). getch().a[20].nc).

C Programs By VINOD

{

clrscr();

printf("Enter no. of elements in the list:- ");

scanf ("%d",&l);

printf("CHOICE:-");

printf("(1) Sort in ascending order.");

printf("(2) Sort in descending order.");

printf("CHOICE:- ");

scanf("%d",&c);

if (c!=1 && c!=2)

{

printf("ERROR");

getch();

exit(0);

}

sort();

getch();

}

void sort(void)

{

int n,i,j,temp=0,min,k;

50

C Programs By VINOD

for (i=1;i<=l;i++)

{

printf("Enter no.:- ");

scanf("%d",&a[i]);

}

for (i=1;i<=(l-1);i++)

{

min=a[i];

k=i;

for (j=(i+1);j<=l;j++)

{

if (a[j]<min)

{

min=a[j];

k=j;

}

}

temp=a[k];

a[k]=a[i];

a[i]=temp;

}

switch(c)

51

C Programs By VINOD

{

case 1:

printf("Elements in ascending order are:-");

for (i=1;i<=l;i++)

printf("%d",a[i]);

break;

case 2:

printf("Elements in descending order are:-");

for (i=l;i>=1;i--)

printf("%d",a[i]);

break;

default:

printf("ERROR");

}

return;

}

/*Printint a double */

#include<stdio.h>

#include<conio.h>

void main(void)

52

C Programs By VINOD

{

int i,j,k,l,b,n;

clrscr();

printf("Enter the value of N:");

scanf("%d",&n);

for(i=0;i<n;i++)

{

printf("\n");

for(l=0;l<i;l++)

printf("\n");

for(j=i+1;j<=n;j++)

printf("%d",j);

for(k=n-1;k>i;k--)

printf("%d",k);

}

b=n-1;

for(i=0;i<n-1;i++)

{

printf("\n");

for(l=n-2;l>i;l--)

printf("\n");

for(j=b;j<=n;j++)

53

Hexadecimal Conversions*/ /*Program for Binary.h> void bd().k>=b.C Programs By VINOD printf("%d". Octal.h> #include<string. 54 . b--. void ob(). void doc(). } /*Program for Binary.j). } getch(). void dh(). Hexadecimal Conversions*/ #include<stdio.h> #include<conio.k). Octal.k--) printf("%d". for(k=n-1. void od(). void db().

"). void main() { int n."). printf("4. void hb(). Octal to Binary. printf("1. void oh().(1-12)")."). void ho(). begin: clrscr()."). Decimal to Octal. Binary to Decimal. Binary to Octal. Decimal to Binary. 55 ."). char c. printf("Enter your choise."). printf("6. printf(" ****MAIN MENU****")."). Decimal to Hexadecimal. printf("2. void bh(). printf("8. printf("5. printf("3. printf("7. void hd()."). Octal to Decimal.C Programs By VINOD void bo(). Binary to Hexadecimal.

scanf("%ld". else if(n==2) db(). if(n<1 || n>12) printf("Invalid Choise"). Hexadecimal to Decimal. } else if(n==5) 56 . Hexadecimal to Octal.")."). scanf("%d". Hexadecimal to Binary. else if(n==4) { long a.C Programs By VINOD printf("9. printf("11. printf("12.&n). printf("Conversion from Decimal to Hexadecimal").")."). clrscr(). dh(a). Octal to Hexadecimal. printf("10."). printf("Enter the decimal number.&a). if(n==1) bd(). else if(n==3) doc().

i=0.C Programs By VINOD od(). else if(n==9) hb(). else if(n==10) hd().p=1.t=0.&n). else if(n==6) ob().a. clrscr(). else if(n==7) bo(). else if(n==11) { unsigned long n. printf("Enter a Octal number"). else if(n==8) bh(). scanf("%ld". printf("Conversion from Octal to Hexadecimal. if(a>7) 57 . i=0."). while(n!=0) { a=n%10.

} if(t==0) { printf("Hexadecimal eq="). getch(). } else if(n==12) ho(). n=n/10. } 58 ."). i=i+a*p. printf("Do you Wish to continue(Y/N)"). p=p*8.C Programs By VINOD t=1. oh(i). scanf("%s". if(c=='Y') goto begin.&c). } else if(t==1) printf("Numbert entered is not octal. c=toupper(c).

while(n!=0) { a[i]=n%10. for(i=0. n=n*2. } a[i]=2. scanf("%d". n=n/10. printf("Conversion from Binary to Decimal").C Programs By VINOD void bd() { int n.&n).i=0. i++.a[i]!=2. n=1.b=0. printf("Enter Binary Number"). } if(t==0) 59 .a[6]. if(a[i]!=1 && a[i]!=0) t=1.t=0. clrscr().i++) { b=b+a[i]*n.

for(n=i-1. printf("Input decimal no. clrscr().n--) printf("%d".a[10].&dec).n>=0.b).a[n]).")."). } void db() { int dec.n.C Programs By VINOD printf("Decimal Equivalent=%d". dec=dec/2. }while(dec!=0). i++. else if(t==1) printf("Entered number is not binary.i=0. do { a[i]=dec%2. printf("Conversion from Decimal to Binary"). } 60 .bin. scanf("%d".

n).i--) printf("%d". while(n!=0) { a[i]=n%8. 61 .i. i=0. n=n/8. } i--.C Programs By VINOD void doc() { int n. printf("Octal equavalent of %d is ". i++. } void dh(long n) { long i.a[i]). printf("Enter a Decimal number").a[10].i>=0. printf("Conversion from Decimal to Octal"). for(. clrscr(). scanf("%d".&n).

break. break. case 14: printf("E"). case 13: printf("D"). if(i>=10) { switch(i) { case 10: printf("A"). dh(n). break. break. case 11: printf("B").C Programs By VINOD if(n>0) { i=n%16. case 12: printf("C"). 62 . n=n/16.

while(n!=0) { a=n%10.t=0.C Programs By VINOD break. printf("Enter a Octal number").n). i=0. scanf("%ld". printf("Conversion from Octal to Decimal"). printf("Decimal equavalent of %ld". case 15: printf("F").&n).i). 63 .i=0. } } void od() { unsigned long n. } } else printf("%ld".p=1. break.a. clrscr().

i=0. printf("Convertion from Octal to Binary."). n=n/10.C Programs By VINOD if(a>7) t=1.i)."). i=i+a*p. while(n!=0) { a[i]=n%10. else if(t==1) printf(" can't be calculated because it is not an Octal Number. p=p*8. } void ob() { int n. n=n/10. clrscr(). } if(t==0) printf("= %ld". printf("Enter an Octal Number.").&n).t=0. 64 . scanf("%d".a[6].

case 2: printf("010").i--) { switch(a[i]) { case 0: printf("000"). i++. break. break. break. case 1: printf("001"). if(t==0) for(.i>=0. case 4: 65 . } i--. break.C Programs By VINOD if(a[i]>7) t=1. case 3: printf("011").

break. break.a[5]. } } if(t==1) printf("Not a Octal number"). break. } void bo() { int i=0. break. case 6: printf("110"). long int n.C Programs By VINOD printf("100").t=0. printf("Convertion From Binary to Octal"). case 5: printf("101"). 66 . clrscr(). case 7: printf("111").

break. } i--. scanf("%ld".i>=0. n=n/1000. case 1: printf("1").i--) { switch(a[i]) { case 0: printf("0"). i++.&n). if(a[i]>111) t=1. case 10: 67 . while(n!=0) { a[i]=n%1000. break. if(t==0) for(.C Programs By VINOD printf("Enter a Binary number").

case 100: printf("4"). case 111: printf("7"). case 11: printf("3"). case 101: printf("5").Printed value is notcorrect. } } if(t==1) 68 . break. case 110: printf("6").C Programs By VINOD printf("2"). break. break. default: printf("Entered number is not binary. break. break. break. break.").

long int n. while(n!=0) { a[i]=n%10000. if(t==0) for(.t=0. n=n/10000. printf("Enter a Binary number"). scanf("%ld". } i--. printf("Convertion from Binary to Hexadecimal"). } void bh() { int i=0.i--) { 69 .a[5]. clrscr().C Programs By VINOD printf("Number is not Binary"). i++.i>=0. if(a[i]>1111) t=1.&n).

break. break. case 100: printf("4"). case 10: printf("2"). case 1: printf("1"). break. break. 70 . break. case 11: printf("3"). break.C Programs By VINOD switch(a[i]) { case 0: printf("0"). case 110: printf("6"). break. case 101: printf("5").

break. break. case 1001: printf("9"). break. break. break. case 1110: printf("E"). case 1101: printf("D"). 71 . case 1100: printf("C"). break.C Programs By VINOD case 111: printf("7"). case 1000: printf("8"). case 1011: printf("B"). case 1010: printf("A"). break.

*/ 72 . clrscr(). default: printf("Entered number is not binary. break. /*gets(s).Printed value is notcorrect. printf("Convertion from Hexadecimal to Binary"). scanf("%s". printf("Enter a Hexadecimal number"). } void hb() { int i. case 1111: printf("F").C Programs By VINOD break.s). char s[20]. } } if(t==1) printf("Number is not Binary"). break.").

break. break. case '5': printf("0101"). break. for(i=0.s[i]!=NULL. case '1': printf("0001"). break. 73 . case '2': printf("0010"). break.C Programs By VINOD printf("Binary Equivalent="). case '4': printf("0100"). break.i++) { switch(s[i]) { case '0': printf("0000"). case '3': printf("0011").

break. break. case '9': printf("1001"). 74 .C Programs By VINOD case '6': printf("0110"). break. break. case 'b': case 'B': printf("1011"). break. case '8': printf("1000"). break. case 'c': case 'C': printf("1100"). case '7': printf("0111"). case 'a': case 'A': printf("1010").

} } } void hd() { int i. default: printf("Entered number is not Hexadecimal.").a[20]. break. 75 . case 'f': case 'F': printf("1111"). break. break. case 'd': case 'D': printf("1101").Printed value is notcorrect. case 'e': case 'E': printf("1110"). break.C Programs By VINOD break.

s).i++) { switch(s[i]) { case '0': a[i]=0. char s[20]. clrscr(). for(i=0. printf("Decimal Equivalent="). case '1': a[i]=1.m=1. break. break. printf("Convertion from Hexadecimal to Decimal"). case '2': a[i]=2.C Programs By VINOD unsigned long int h=0. printf("Enter a Hexadecimal number"). 76 . scanf("%s". case '3': a[i]=3. break.s[i]!=NULL. break.

case '6': a[i]=6. break. break. case '7': a[i]=7. break. break. break. case '8': a[i]=8. case 'b': 77 .C Programs By VINOD case '4': a[i]=4. case '9': a[i]=9. case 'a': case 'A': a[i]=10. case '5': a[i]=5. break. break.

break. default: printf("Entered number is not Hexadecimal. case 'd': case 'D': a[i]=13.Printed value is notcorrect. break. break.").C Programs By VINOD case 'B': a[i]=11. case 'e': case 'E': a[i]=14. break. } 78 . break. case 'f': case 'F': a[i]=15. case 'c': case 'C': a[i]=12. break.

oh(n).C Programs By VINOD } i--.h). } printf("%ld ". if(n>0) { i=n%16. } void oh(long n) { long i. m=m*16. for(.i--) { h=h+a[i]*m. if(i>=10) { switch(i) { case 10: 79 .i>=0. n=n/16.

C Programs By VINOD printf("A"). break. break. case 15: printf("F"). } } 80 . case 11: printf("B"). break. } } else printf("%ld".i). case 13: printf("D"). case 14: printf("E"). break. break. case 12: printf("C"). break.

break.i++) { switch(s[i]) { case '0': a[i]=0.m=1. char s[20]. scanf("%s". clrscr(). 81 . printf("Convertion from Hexadecimal to Octal"). unsigned long int h=0.C Programs By VINOD void ho() { int i. /* Converting hex to dec first*/ for(i=0.a[20]. break. printf("Enter a Hexadecimal number").s). case '2': a[i]=2. case '1': a[i]=1.s[i]!=NULL.

break. case '7': a[i]=7. break. case '9': a[i]=9. case '8': a[i]=8. case 'a': 82 . break. break. case '4': a[i]=4.C Programs By VINOD break. break. case '3': a[i]=3. case '5': a[i]=5. break. case '6': a[i]=6. break.

C Programs By VINOD case 'A': a[i]=10. 83 . break. case 'c': case 'C': a[i]=12. break. break. break. break. break. case 'e': case 'E': a[i]=14. case 'f': case 'F': a[i]=15. case 'd': case 'D': a[i]=13. case 'b': case 'B': a[i]=11.

i>=0.i--) { h=h+a[i]*m.i>=0."). i++.C Programs By VINOD default: printf("Entered number is not Hexadecimal. m=m*16. 84 .a[i]). for(.Printed value is notcorrect. while(h!=0) { a[i]=h%8. printf("Octal equavalent="). } /* Now convering from decimal to octal (h)*/ i=0. h=h/8. } i--. for(. } } i--. break.i--) printf("%d".

} else if (comp==2) 85 . printf ("choose please: 1=perimeter. printf ("Enter the length: ").C Programs By VINOD } /*Program for computing Area.ans. Volume and Perimeter of Rrectangle using function with looping*/ #include <stdio. scanf ("%d".&le). if (comp==1) { int le. scanf ("%d".&comp).h> void inputoutput () { int comp.2=area.wi)). printf ("Enter the width: ").3=volume] ?: "). printf ("P=%d". clrscr ().perimeter(le.&wi). scanf ("%d". wi.

&width).width.&height). printf ("Do you want to continue? [Yes=1/No=0]: "). scanf ("%d". scanf ("%d". } else if (comp==3) { int length. scanf ("%d".&ans). } else inputoutput (). printf ("V=%d". printf ("Enter lenght: ").&wi).height. area(le. printf ("Enter width: "). printf ("Enter the width: ").&length). scanf ("%d". printf ("Enter height: ").&le).height)). printf ("Enter the length: "). wi.volume (length. scanf ("%d".C Programs By VINOD { int le.wi)). 86 . scanf ("%d". printf ("A=%d".width.

} int area (int le. per=(l*2)+(w*2). vol=(length*width*height). return (are).C Programs By VINOD if (ans==1) inputoutput (). } int perimeter (int l. int w) { int per. are=le*wi. int height) { int vol. int width. return (per). return (vol). 87 . int wi) { int are. } int volume (int length. else printf ("GOOD BYE").

inputoutput ().m.h> void main() { int n. } /*Program for finding the prime numbers*/ #include <stdio. clrscr(). getch ().C Programs By VINOD } main () { clrscr ().h> #include <conio. repeat: max=0.i. 88 . k=2. char c.k.max.

printf("").i++) { again: m=(n/k)*k. } fflush(stdin)."). else printf("%d". try1: n=n+1.n). if (c=='y') 89 . printf ("Do you want to continue?(y/n):.i<=max. if (k < n/2) goto again.C Programs By VINOD n=1. if (m!=n) k=k+1.").&c).&max). printf(" "). scanf("%d". printf("You want prime numbers upto:. for (i=1. else goto try1. scanf("%c". k=2.

".o.r. repeat: s=0.p.q.s). q=p%100. getch(). printf("The sum of its digits is %d.h> void main() { int n. o=n%10000. 90 . } /*Program for finding the sum of digits of a five digit number*/ #include <stdio.h> #include <conio. s=(n/10000)+(o/1000)+(p/100)+(q/10)+r.s. r=q%10.C Programs By VINOD goto repeat.:. p=o%1000.&n)."). char c. clrscr(). scanf("%d". printf("Enter a five digit no.

j<=i.i=1."). if (c=='y') goto repeat. scanf("%c". printf ("Do you want to continue?(y/n):. printf("Enter Number Of Terms").j++) 91 . while(i<=n) { c=0.j.h> main() { int n.c. } /*Program for Prime Number Generation*/ #include <stdio.&n). printf("Prime Numbers Are Follwing"). clrscr(). for(j=1.&c).C Programs By VINOD fflush(stdin). scanf("%d". getch().

i++.h> #define ROT 13 int main(void) { int c. } if(c==2) printf("%d ".C Programs By VINOD { if(i%j==0) c++. } /*Program Implementing the rot13 algorithm*/ #include<stdio.e. while((c=getchar())!=EOF) { if(c >='A' && c <='Z') 92 . } getch().i).

else { e = c .C Programs By VINOD { if((e = c + ROT) <= 'Z') putchar(e). putchar(e).ROT. } } else if(c >='a' && c <='z') { if((e= c + ROT) <= 'z') putchar(e). } } else putchar(c). } 93 . else { e = c . putchar(e).ROT.

C Programs By VINOD

return 0;

}

/*Program of Falling Characters*/

#include<stdio.h>

#include<conio.h>

#include<dos.h>

#include<string.h>

void main()

{

int i,j,l,t;

char y[20];

clrscr();

printf("Enter a string");

gotoxy(2,2);

gets(y);

l=strlen(y);

t=1;

for(j=0;j<l;j++,t++)

{

for(i=3;i<=24;i++)

94

C Programs By VINOD

{

clrscr();

puts(y);

gotoxy(t,i);

printf("%c",y[j]);

delay(100);

}

}

clrscr();

getch();

}

/*Program to calculate frequency of vowels in a string*/

#include <stdio.h>

#include <conio.h>

void main()

{

int a=0,e=0,i=0,o=0,u=0,sum=0;

char c;

clrscr();

printf("Enter string:- ");

printf("String will be terminated if you press Ctrl-Z & then ENTER.");

95

C Programs By VINOD

printf("STRING:- ");

while ((c=getchar())!=EOF)

{

if (c=='a'||c=='A')

a=a+1;

if (c=='e'||c=='E')

e=e+1;

if (c=='i'||c=='I')

i=i+1;

if (c=='o'||c=='O')

o=o+1;

if (c=='u'||c=='U')

u=u+1;

}

sum=a+e+i+o+u;

printf("Frequency of vowel 'a' is %d.",a);

printf("Frequency of vowel 'e' is %d.",e);

printf("Frequency of vowel 'i' is %d.",i);

printf("Frequency of vowel 'o' is %d.",o);

printf("Frequency of vowel 'u' is %d.",u);

printf("Total no. of vowels in the text is %d.",sum);

printf("HAVE A NICE DAY! BYE.");

getch();

96

C Programs By VINOD

}

/*Program to Calculate the Pascal triangle*/

#include<stdio.h>

#include<conio.h>

void main()

{

int a[10][10];

int i,j,c,n;

clrscr();

printf("Enter how many lines do you want");

scanf("%d",&n);

a[1][1]=1;

printf("%5d",a[1][1]);

a[2][1]=1;a[2][2]=2;a[2][3]=1;

printf("%d %d %d",a[2][1],a[2][2],a[2][3]);

for(i=3;i<=n;i++)

{

a[i][1]=1;

printf("%d",a[i][1]);

j=2;c=3;

while(j<=i)

97

h> long int factorial(int n). } getch(). printf("%5d".a[i][j]).C Programs By VINOD { a[i][j]=a[i-1][c-1]+a[i-1][c-2]. printf("%d". 98 . char c.h> #include <conio.r. j=j+1.i.a[i][j]). } a[i][j]=1. } /*Program to calculate the sum of series*/ #include <stdio. void main() { int n. float s. c=c+1.

if (c=='y') goto repeat. return(n). repeat : printf("You have this series:.n."). } printf("The sum of %d terms is %f".i++) { s=s+((float)i/(float)factorial(i)).C Programs By VINOD clrscr().. for (i=1. printf ("Do you want to continue?(y/n):. scanf("%d". scanf("%c".&n). fflush(stdin).s). else n=n*factorial(n-1). 99 .1/1! + 2/2! + 3/3! + 4/4! . getch().i<=n.&c)."). s=0.. printf("To which term you want its sum? "). } long int factorial(int n) { if (n<=1) return(1).

i<=n. void main() { int n. for (i=1. char c.").. s=0. repeat : printf("You have this series:. printf("To which term you want its sum? ").i.C Programs By VINOD } /*Factorial Function*/ #include <stdio.1/1! + 2/2! + 3/3! + 4/4!.i++) { s=s+((float)i/(float)factorial(i)).h> long int factorial(int n). scanf("%d".h> #include <conio. clrscr(). } 100 . float s.&n).r.

C Programs By VINOD printf("The sum of %d terms is %f". return(n).n. getch().&c).s).h> 101 .h> #include <conio. else n=n*factorial(n-1). } /* Prg. fflush(stdin). to convert upper case to lower case or lower case to upper case depending on the name it is invoked with as found in argument."). } long int factorial(int n) { if (n<=1) return(1). printf ("Do you want to continue?(y/n):.*/ #include <stdio. scanf("%c". if (c=='y') goto repeat.

"). switch (n) { case 1: { printf("Please enter a string in upper case. printf("STRING:.").")."). break. upper_to_lower()."). printf("(2) for lower to upper conversion. void upper_to_lower(). printf("String will be terminated if you press Ctrl-Z. printf("(1) for upper to lower conversion. printf("Please enter your choice.&n). clrscr(). scanf("%d". void main() { int n. } 102 ."). printf("CHOICE:.C Programs By VINOD void lower_to_upper().").

break. char c4[80]."). for (j=0. } default: printf("ERROR")."). printf("STRING:. for (i=0.").j.c3.C Programs By VINOD case 2: { printf("Please enter a string in lower case. getch().(c3=getchar())!=EOF. } printf("HAVE A NICE DAY! BYE.i++) c4[i]=(c3>='A' && c3<='Z')?('a' + c3 -'A'):c3.j++) putchar(c4[j]). printf("String will be terminated if you press Ctrl-Z."). 103 . printf("The lower case equivalent is "). lower_to_upper(). } void upper_to_lower() { int i.j<i.

C Programs By VINOD

return;

}

void lower_to_upper()

{

int i,j;

char c2[80],c1;

for (i=0;(c1=getchar())!=EOF;i++)

c2[i]=(c1>='a' && c1<='z')?('A' + c1 -'a'):c1;

printf("The upper case equivalent is ");

for (j=0;j<i;j++)

putchar(c2[j]);

return;

}

/*Program to compute difference between two dates*/

#include<stdio.h>

#include<math.h>

void main()

{

int day1,mon1,year1,day2,mon2,year2;

int ref,dd1,dd2,i;

104

C Programs By VINOD

clrscr();

printf("Enter first day, month, year");

scanf("%d%d%d",&day1,&mon1,&year1);

scanf("%d%d%d",&day2,&mon2,&year2);

ref = year1;

if(year2<year1)

ref = year2;

dd1=0;

dd1=func1(mon1);

for(i=ref;i<year1;i++)

{

if(i%4==0)

dd1+=1;

}

dd1=dd1+day1+(year1-ref)*365;

printf("No. of days of first date fronm the Jan 1 %d= %d",year1,dd1);

/* Count for additional days due to leap years*/

dd2=0;

for(i=ref;i<year2;i++)

{

if(i%4==0)

dd2+=1;

}

105

C Programs By VINOD

dd2=func1(mon2)+dd2+day2+((year2-ref)*365);

printf("No. of days from the reference year's first Jan = %d",dd2);

printf("Therefore, diff between the two dates is %d",abs(dd2-dd1));

getch();

}

int func1(x) /*x for month y for dd*/

{ int y=0;

switch(x)

{

case 1: y=0; break;

case 2: y=31; break;

case 3: y=59; break;

case 4: y=90; break;

case 5: y=120;break;

case 6: y=151; break;

case 7: y=181; break;

case 8: y=212; break;

case 9: y=243; break;

106

C Programs By VINOD

case 10:y=273; break;

case 11:y=304; break;

case 12:y=334; break;

default: printf("Error encountered"); exit(1);

}

return(y);

}

Prg. to sort any no. of numeral i-p in ascending or descending order.

#include<stdio.h>

#include<conio.h>

void sort(void);

int c,a[20],l;

void main()

{

clrscr();

printf("Enter no. of elements in the list:- ");

scanf ("%d",&l);
107

"). getch().:. if (c!=1 && c!=2) { printf("ERROR").temp=0. scanf("%d".min. printf("(2) Sort in descending order. printf("CHOICE:.&c). printf("(1) Sort in ascending order. getch(). } for (i=1.").i<=l. for (i=1.j.i++) 108 .C Programs By VINOD printf("CHOICE:-"). } sort().").i. exit(0)."). } void sort(void) { int n. scanf("%d".i++) { printf("Enter no.k.&a[i]).i<=(l-1).

j<=l.i++) printf("%d". for (i=1. for (j=(i+1). 109 . case 2: printf("Elements in descending order are:-").C Programs By VINOD { min=a[i]. } switch(c) { case 1: printf("Elements in ascending order are:-").a[i]).j++) { if (a[j]<min) { min=a[j]. a[i]=temp. a[k]=a[i].i<=l. } } temp=a[k]. k=i. break. k=j.

} /*Merge sort*/ #include<stdio.i++) { scanf("%d". break. printf("enter the data:"). default: printf("ERROR").int n) 110 . } } void display(int arr[].i>=1.i--) printf("%d".C Programs By VINOD for (i=l. for(i=0.a[i]).h> void getdata(int arr[].i<n.int n) { int i.&arr[i]). } return.

} getchar().arr[i]). } void sort(int arr[]. while((l<=mid)&&(j<=high)) { if(arr[l]<=arr[j]) { b[i]=arr[l].int high) { int i.i++) { printf("%d ".j. j=mid+1.i<n.l. l=low.int mid. for(i=0.b[20].C Programs By VINOD { int i. } else { 111 . printf("").int low. l++. i=low.k.

} } for(k=low.k<=high. i++.k++) { b[i]=arr[k].k<=high.k++) { b[i]=arr[k]. } } else { for(k=l. } i++. i++.k++) { arr[k]=b[k]. j++. } 112 .C Programs By VINOD b[i]=arr[j].k<=mid. } if(l>mid) { for(k=j.

partition(arr. getdata(arr.n). partition(arr. 113 . sort(arr.0.mid.int high) { int mid.&n). } } void main() { int arr[20]. display(arr. partition(arr. getchar().high).high).low.mid).C Programs By VINOD } void partition(int arr[].n-1). if(low<high) { mid=(low+high)/2.mid+1.int low. scanf("%d".n).low. printf("Enter number of data:"). int n.

/*Random no generation*********************** */ 114 . void calno(int).tiger.check.n.h> #include<stdlib. clrscr(). int i.score=1000.C Programs By VINOD } /*No guessing*/ #include<conio. char ch. void main(){ int x[4].h> int no=0.h> #include<stdio.h> #include<process.j.count.goat.m.k. int client[4].

while(1){ x[0]=random(9). if(x[2]!=x[1]&&x[2]!=x[0]) break.i++){ 115 .i<4. } while(1){ x[2]=random(9). if(x[0]!=0) break. } while(1){ x[3]=random(9). if(x[3]!=x[2]&&x[3]!=x[1]&&x[3]!=x[0]) break. if(x[0]!=x[1]) break.C Programs By VINOD randomize(). } /* ******************************************** */ for(i=0. } while(1){ x[1]=random(9).

count++){ if(x[count]==client[count]) tiger=tiger+1. /* starting of guessing****************** */ for(i=1. printf("Enter the %d guess: ". printf("^^^^^^^^^Now you will have to guess the no^^^^^^^^:").count<4. goat=0.&ch).i++){ tiger=0.x[i]). } printf(" -----This is a game of goat and tiger------").i).The no should be 4 digit no without 0 in the first place"). printf("________________________________________"). 116 .&check).i<=10. printf("-------------------------------------------------------"). scanf("%d".C Programs By VINOD printf("%d". if(ch=='n'||ch=='N') exit(0). printf("1. printf("***First read these instructions***"). calno(check). for(count=0. The digit shouldn't be reapeated"). printf("2. scanf("%c". printf("Do you agree the agreement and ready for the game(Y/N): ").

score=score-100. } } } printf(" and %d goat".C Programs By VINOD } printf("You have got %d tiger". for(j=0. /*---------------check for goat----------------------*/ for(m=0.n<4.j<4. if(tiger==4) break.x[j]). printf("the no is "). } if(tiger<4){ printf("-----Sorry u have lost the game-----").tiger).n++){ if(client[m]!=x[m]){ if(client[m]==x[n]) goat=goat+1. } } 117 .goat).m<4.j++){ printf("%d".m++){ for(n=0.

getch(). client[2]=x%10. client[1]=y%10. x=a/10. y=a/100.h> #define FIRST 0 118 . client[0]=a/1000.h> #include<conio. client[3]=a%10.score).j.C Programs By VINOD else printf("-----You have got the no in %d guess and you score is%d----".y. } void calno(int no){ int a=no. } Invoke function without main in C Language #include<stdio.x.

b.ch. //Function Prototype void Read().C Programs By VINOD #define SECOND 1 #define THIRD 2 //Variables int a. getch(). void Operation(). #pragma startup Read 0 //First_Priority #pragma startup Operation 1 //Second_Priority #pragma exit Display //Third_Priority void main() { printf(" Enter to main() "). printf(" Exit From main() "). float d.c. void Display(). 119 .

} void Read() { clrscr(). } void Operation() { printf(" ArithMetic Operations ").&a). 120 . printf("--------------------- "). printf("2 -> Subtraction ").C Programs By VINOD getch(). printf("1 -> Addition "). scanf("%d". printf(" Enter the value of a : "). scanf("%d".&b). printf(" Enter the value of b : ").

case 2: c = a-b.C Programs By VINOD printf("3 -> Multiplication "). printf("--------------------- "). break. case 3: c = a*b. } } void Display() { switch(ch) { case 1: printf(" 121 .&ch). break. break. scanf("%d". switch(ch) { case 1: c = a+b.

} getch(). case 3: printf(" The Result (Multiplication): %d". break.h> 122 . break.c).c).h> #include<conio.C Programs By VINOD The Result (Addition) : %d". break. } Calendar of Thousands of Years #include<stdio. case 2: printf(" The Result (Subtraction): %d".c).

int d. "November". long int ndays.28. scanf("%d%d". "September".31.30. "March".31}. "October".30. textcolor(LIGHTGREEN). void main() { static int days[12]={31. "July". "August". while(1) { 123 . "December"}.y. textbackground(LIGHTBLUE). "April". char ch.&m).31. printf("Enter year(1900 onwards) & month(number):").&y.tdays.m.fday. clrscr().31.C Programs By VINOD static char *months[]={"January".31.ldays.i. "May". "February".30.31. "June".tydays.30.

cal(y. } else 124 .fday.m. ch=getche().//total days //check for leap year if((y%100==0 && y%400==0)||(y%4==0 && y%100!=0)) days[1]=29. switch(ch) { case 77: if(m==12) { y++.i<=m-2. ldays=(y-1)/4-(y-1)/100+(y-1)/400. for(i=0. d=days[m-1]. tdays=tydays+tdays.C Programs By VINOD ndays=(y-1)*365l. fday=tdays%7. tdays=ndays+ldays. else days[1]=28.i++) tydays=tydays+days[i]. tydays=0. m=1.d).

c. clrscr(). }}} cal(int yr. break.C Programs By VINOD m++. break. continue. continue. } else m--.int da) { int i. case 75: if(m==1) { y--.r. case 27: exit(0).int mo. case 72: y++. case 80: y--.int fd. 125 . char a. m=12.

r).7). gotoxy(5.C Programs By VINOD gotoxy(25. c=11+(6*fd). else textcolor(LIGHTGREEN).5).2). else { c=11.i++) { gotoxy(c. if(c==47) textcolor(RED).months[mo-1]. printf("%s %d". r=9. textcolor(LIGHTGREEN). printf("MON TUE WED THU FRI SAT SUN"). gotoxy(10. cprintf("%d".yr). gotoxy(5. 126 .i).i<=da.6). for(i=1. printf("____________________________________________________"). printf("____________________________________________________"). if(c<=41) c=c+6. r=r+1.

gotoxy(27.h> #include <conio. gotoxy(11.20). printf("____________________________________________________"). printf("UP-Next Year DOWN-Prev Year"). printf("Esc-Exit").h> #include <ctype. return 0. printf("RIGHT-Next Month LEFT-Prev Month"). gotoxy(11.C Programs By VINOD } } textcolor(LIGHTGREEN).h> #include <process.15). 127 .h> unsigned long days=0. } /*Calender Program in C*/ /*Program to display calender for a given year*/ #include <stdio.17).18). gotoxy(5.

} 128 .01. flag=0. j./*remainder gives the starting day of each month*/ if(flag==0) { for(j=1. i++) { k=days%7. getch(). column++. j<=k. if(column%7==0)/*prints new line at the end of each week*/ printf(""). } printf("Press any key to continue"). i). k.C Programs By VINOD /*stores the days elapsed since 01. j++)/*controls tabs of first week*/ printf(" "). for(i=1. flag=1. i<=n./*ensures that block is only executed once*/ column=k. } printf("%d ".1899*/ void display(int n) /*contains the number of days to display*/ { int i. column. printf("Sun Mon Tues Wed Thur Fri Sat").

then it is not a leap year. 1899 is a Sunday*/ { if((i%400==0)?1:((i%100==0)?0:((i%4==0)?1:0))) /*This is because a leap year does not strictly fall on every fourth year. if the year is also divisible by 400. month++) { printf(""). then it is a leap year. Eg: 1900 is not a leap year*/ days+=366. } for(month=1. However.C Programs By VINOD void calculate(int year) /*function calculates no. month. month<=12. i++) /*1899 chosen because Jan 1. switch(month) /*switch case used to display each month and increment no. If a year is divisible by 4. else days+=365. i<year. but if that year is divisible by 100. for(i=1899. then it is a leap year. of days elapsed since 1899*/ { int i. of days*/ 129 .

display(31). year). if((year%400==0)?1:((year%100==0)?0:((year%4==0)?1:0))) { display(29). case 3: printf(" MARCH %d". display(30). days+=30. break. case 4: printf(" APRIL %d". days+=28. display(31). case 2: printf(" FEBURARY %d". 130 . days+=31. break.C Programs By VINOD { case 1: printf(" JANUARAY %d". year). } else { display(28). } break. break. days+=31. year). days+=29. year).

days+=30. display(31). case 9: printf(" SEPTEMBER %d". break. case 7: printf(" JULY %d". year). break. case 11: printf(" NOVEMBER %d". days+=31. display(31). days+=30. break. year). case 8: printf(" AUGUST %d". break. year). display(31). break. year).C Programs By VINOD case 5: printf(" MAY %d". days+=31. display(30). case 6: printf(" JUNE %d". display(30). break. case 10: printf(" OCTOBER %d". year). days+=31. 131 . display(31). days+=31. year). year).

int i. break. ch). i<strlen(ch). 132 . printf("Enter the year in 'yyyy' format:"). display(31). days+=30./*stores input first as a string*/ for(i=0. do { clrscr().C Programs By VINOD display(30). days=0. i++) if(ch[i]<'0' || ch[i]>'9')/*checks for invalid inputs*/ { printf("Invalid Year!"). } } } void main() { char ch[10]. choice. days+=31. case 12: printf(" DECEMBER %d". year). break. year. scanf("%s".

/*converts the year from string to integer datatype*/ clrscr(). getch(). printf("Calender for Year %d". of days elapsed*/ printf("*******************************************"). } year = atoi(ch). }while(choice==1). /*calls function to calculate no. scanf("%d". } INTERVIEW QUESTIONS C Predict the output or error(s) for the following: 133 . year). printf("END OF PROGRAM"). calculate(year). 2 to exit"). exit(0). printf("**********************"). printf("Press 1 to continue. getch(). &choice).C Programs By VINOD printf("END OF PROGRAM"). clrscr().

} Answer: mmmm aaaa nnnn 134 .*(s+i).++(*p)). 2. void main() { int const * p=5. But we tried to change the value of the "constant integer". Explanation: p is a pointer to a "constant integer". main() { char s[ ]="man".i++) printf(" %c%c%c%c".C Programs By VINOD 1. for(i=0.s[ i ].i[s]). int i.s[ i ]. } Answer: Compiler error: Cannot modify a constant value.*(i+s). printf("%d".

1. double. double you = 1. *(s+i). indirecting it with * is same as s[i]. 3. Depending on the number of bytes. main() { float me = 1. So.C Programs By VINOD Explanation: s[i]. i is the index number/displacement from the base address. But in the case of C it is same as s[i]. Here s is the base address. Generally array name is the base address for that array. the precession with of the value represented varies. else printf("I hate U"). if(me==you) printf("I love U"). *(i+s). i[s] are all different ways of expressing the same idea.1. i[s] may be surprising. } Answer: I hate U Explanation: For floating point numbers (float. long double) the values cannot be predicted exactly. Float takes 4 bytes and long 135 .

} Answer: 54321 Explanation: When static storage class is given. 4. main() 136 . >=.!= ) . which can be called recursively. <=. printf("%d ". Main is also treated like any other ordinary function. Rule of Thumb: Never compare or at-least be cautious when using floating point numbers with relational operators (== .C Programs By VINOD double takes 10 bytes. The change in the value of a static variable is retained even between the function calls. <. it is initialized once.9 with less precision than long double. main() { static int var = 5. So float stores 0.var--). if(var) main(). >. 5.

So the values 2 3 4 6 5 will be printed. since only q is incremented and not c .j<5. for(j=0.j<5. i=20.*p).*q=c. } for(j=0.*c).C Programs By VINOD { int c[ ]={2.j++) { printf(" %d ". ++p. 6.6.7. 137 . main() { extern int i. ++q.j++){ printf(" %d ".8.4.*p=c. int j. In second loop p itself is incremented. the value 2 will be printed 5 times.4.5}. } } Answer: 2222223465 Explanation: Initially pointer c is assigned to both p and q. In the first loop.3.

But linker finds that no other variable of name i is available in any other program with memory space allocated for it.k. specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. main() { int i=-1. } Answer: 00131 138 .C Programs By VINOD printf("%d". m=i++&&j++&&k++||l++.j. extern int i.m). Hence a linker error has occurred .l. } Answer: Linker Error : Undefined symbol '_i' Explanation: extern storage class in the following declaration. 7.k=0.i.j=-1.m.l=2.i). printf("%d %d %d %d %d".

printf("%d %d ".for which it gives 0).sizeof(*p). So the value of m is 1. The result of this expression is 0 (-1 && -1 && 0 = 0). P is 139 . 8. The values of other variables are also incremented by 1. Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’ combination. main() { char *p. } Answer: 12 Explanation: The sizeof() operator gives the number of bytes taken by its operand. And also the logical AND (&&) operator has higher priority over the logical OR (||) operator.sizeof(p)). So the expression ‘i++ && j++ && k++’ is executed first.C Programs By VINOD Explanation : Logical operations always give a result of 1 or 0 .

It is executed only when all other cases doesn't match. case 2:printf("two"). case 1: printf("one").C Programs By VINOD a character pointer. case 3: printf("three"). main() { int i=3. which needs one byte for storing its value (a character). } } Answer : three Explanation : The default case can be placed anywhere inside the loop. break. break. 140 . break. switch(i) { default:printf("zero"). Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2. Hence sizeof(*p) gives a value of 1. 9.

display(string). the compiler 141 .string). 11. } Answer: fff0 Explanation : -1 is internally represented as all 1's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.-1<<4). when the function display is encountered. main() { char string[]="Hello World". } Answer: Compiler Error : Type mismatch in redeclaration of function display Explanation : In third line. When left shifted four times the least significant 4 bits are filled with 0's.C Programs By VINOD 10. } void display(char *string) { printf("%s". main() { printf("%x".

Explanation: Here unary minus (or negation) operator is used twice. (which is the default type). 12. i--). Note: However you cannot give like --2. Hence a compile time error occurs.. minus * minus= plus.c). printf("c=%d". main() { int c=. Because -.-2. 2 is a constant and not a variable.operator can only be applied to variables as a decrement operator (eg.C Programs By VINOD doesn't know anything about the function display. the arguments and type contradicts with what it has assumed previously. It assumes the arguments and return types to be integers. 142 . When it sees the actual function display. } Answer: c=2. Same maths rules applies. ie.

C Programs By VINOD 13. i=!i>14. printf("i=%d".sizeof(i)). } Answer: sizeof(i)=1 Explanation: Since the #define replaces the string int by the macro char 14. #define int char main() { int i=65. main() { int i=10.i). } Answer: i=0 Explanation: In the expression !i>14 . printf("sizeof(i)=%d". NOT (!) operator has more precedence than ‘ >’ 143 .

' C++ Class with constructor ( for bank account ) # include<iostream. 0>14 is false (zero).C Programs By VINOD symbol.h> # include<conio. #include<stdio.' '.h> main() { char s[]={'a'. !i (!10) is 0 (not of true is false). 144 .'c'.h> # include<iomanip. ! is a unary logical operator.'b'.h> class bank { char name[20]. int acno. 15.'c'.

acno = 0000. void withdraw(). float balance.0. void deposit(). balance = 0. cout<<" 145 . public: // Constuctor bank() { cout<<"Constructor Invoked !". } void init(). void disp_det(). //member functions of bank class void bank :: init() { cout<<" New Account ".C Programs By VINOD char actype[4]. }.

cin>>actype. cout<<" Enter the Amount to Deposit : ".C Programs By VINOD Enter the Name of the depositor : ". cout<<" Enter the amount to deposit : ". cin. } void bank :: deposit() { float more. cout<<" Enter the Account Type : (CURR/SAVG/FD/RD/DMAT) ". 146 .get(name. cout<<" Enter the Account Number : ". cin>>acno. cout <<" Depositing ".' '). cin >>balance.19.

cout<<" Enter the amount to withdraw : ". cout<<" Withdrwal ". cout<<"Name of the depositor : "<<name<<endl. cin>>amt. } void bank :: withdraw() { float amt. 147 . balance-=amt. balance+=more. } void bank :: disp_det() { cout<<" Account Details ".C Programs By VINOD cin>>more.

Withdraw 4. 148 . bank obj. switch(choice) { case 0 :obj. int choice =1. Initialize a new acc.disp_det().C Programs By VINOD cout<<"Account Number : "<<acno<<endl. cin>>choice. } // main function . cout<<"Balance : \$"<<balance<<endl. exectution starts here void main(void) { clrscr(). 2.See A/c Status". cout<<"Account Type : "<<actype<<endl. while (choice != 0 ) { cout<<" Enter 0 to exit 1. Deposit 3.

case 1 : obj. break.withdraw(). case 4: obj. break. } Program to calculate the Typing Speed 149 .init(). case 2: obj.C Programs By VINOD cout<<" EXITING PROGRAM.". default: cout<<" Illegal Option"<<endl. break. case 3 : obj.deposit(). } } getch(). break. break.disp_det().

class Timer { public: Timer().h> #include <conio. double time(). void reset(). void start(). private: 150 .C Programs By VINOD #include <stdio.h> #define ESC 0x1b #define BSPACE 0x08 const unsigned long far * const dosTime = (const unsigned long far * const)MK_FP( 0x40. int status(). void stop(). 0x6C ). static double resolution().h> #include <dos.

double time_. }.E6. unsigned timerCount. inline double Timer::time() { return time_/1. } 151 . } inline double Timer::resolution() { return 839/1. struct TIME { unsigned long dosCount.E9. int running. static unsigned calibrate(). }. TIME startTime.C Programs By VINOD static unsigned adjust.

} } 152 . 0 ). __1: outportb( 0x40.C Programs By VINOD unsigned Timer::adjust = calibrate(). running = 1. startTime. asm jmp __2. Timer::Timer() : time_(0).dosCount = *dosTime. __2: outportb( 0x40. startTime. 0 ).timerCount = 0. asm jmp __1. running(0) { } void Timer::start() { if( !running ) { outportb( 0x43. 0x34 ).

unsigned char temp = inportb( 0x40 ).timerCount = (inportb( 0x40 ) << 8) + temp. const double fudge = 83810. elapsedTime.startTime.dosCount. stopTime.C Programs By VINOD void Timer::stop() { outportb( 0x43.0. running = 0. stopTime.timerCount)*fudge.0/100000.dosCount = stopTime.timerCount .dosCount = *dosTime. 0 ). } void Timer::reset() { 153 . TIME stopTime. elapsedTime.timerCount = -( stopTime.dosCount .adjust ).dosCount << 16) + elapsedTime. time_ += ((elapsedTime. TIME elapsedTime.

} return (unsigned)((sum+5)/100).C Programs By VINOD time_ = 0. if( running ) start(). w.stop().reset(). i++ ) { w.time().start(). for( int i = 0. sum += w. unsigned long sum = 0. Timer w. i < 100. } void main() { 154 . w. } unsigned Timer::calibrate() { adjust = 0.

"). letter_count++.start(). letter_count = 0. if(text[i] == ' ') 155 . Start typing. "). Hit Esc when done. Timer t.C Programs By VINOD clrscr(). char text[1000]. float duration. printf(" PROGRAM TO TEST TYPING SPEED "). printf("Hit any key to start timer. space_count = 0. if(getch()) { printf("Your time has started.. } while(1) { text[i] = getche().. int i = 0. t.

duration = t. // to eliminate a special character that is printed for Esc // A Backspace followed by Space erases previous character. } } t.C Programs By VINOD space_count++. // to erase previous character instead of cursoring over if(text[i] == ESC) { printf(" "). break. printf(" Your typing speed is : 156 . if(text[i] == BSPACE) printf(" "). if(text[i] == ' ') printf(" ").stop().time().

60*letter_count/duration).2f words per minute (Average)".2f words per minute (Actual) ".60*letter_count/duration/5).h> void dtoh(int d). printf("%6.C Programs By VINOD "). } /*Program to convert input decimal value to its hexadecimal equivalent*/ #include <stdio.2f characters per minute ".60*space_count/duration). 157 .h> #include <conio.h> #include <math. getch(). printf("%6. printf("%6.

i=0.c=0.a[5]. c++. printf("Enter a no. dtoh(d). while (b>15) { a[i]=b%16. i++. scanf("%d".C Programs By VINOD main() { int d. b=b/16."). in decimal system:. getch(). printf("\n\nHAVE A NICE DAY! BYE. } 158 .").&d). clrscr(). b=d. } void dtoh(int d) { int b.

C Programs By VINOD a[i]=b. } /*Program to Convert Numbers into Words*/ 159 . else if (a[i]==15) printf("F"). } return.a[i]). printf("Its hexadecimal equivalent is "). else if (a[i]==11) printf("B"). for (i=c.i>=0. else if (a[i]==12) printf("C"). else if (a[i]==13) printf("D").--i) { if (a[i]==10) printf("A"). else printf("%d". else if (a[i]==14) printf("E").

else { pw((n/10000000)." seventeen". clrscr(). void main() { long n.&n)." sixteen"."lakh")." fourteen". if(n<=0) printf("Enter numbers greater than 0")."fifteen"." Nine". scanf("%9ld"." three".char[])." eighty"." ninety"}." two". pw(((n/1000)%100)."eight"." sixty".h> void pw(long. char *one[]={" "." ten"."thousand")." fifty"." one"." seven"." nineteen"}." twenty"." "." twelve"." forty"." five"." eleven"." four"." thirteen"." thirty". char *ten[]={" "."crore")."seventy". printf("Enter any 9 digit no: "). pw(((n/100000)%100)." eighteen". 160 ." six".C Programs By VINOD #include<stdio.

} getch(). clrscr().C Programs By VINOD pw(((n/100)%10).one[n]). } void pw(long n. if(n)printf("%s ".one[n%10]):printf("%s ". } /*Program to copy its input to its output replacing string of one or more blanks by a single blank*/ #include <stdio. pw((n%100).ch)." ")."hundred"). 161 .char ch[]) { (n>19)?printf("%s %s ".ten[n/10].h> void main() { char c.h> #include <conio.

printf("Justified form:. while (c==' ') { c=getchar(). printf("Press Ctrl-Z & then ENTER to end the task.").")."). } getch(). c=getchar(). printf("STRING:."). } 162 . } putchar(c).C Programs By VINOD printf("Enter a line of text:."). c=getchar(). printf("String will be terminated if you press ENTER. while (c!=EOF) { if (c==' ') putchar(c).

").can/'t open file %s".name). printf("Enter the name of file to be checked:. int nw=0. if (fpt==NULL) { printf("ERROR . } else 163 . getch(). exit(0).C Programs By VINOD /*Program to count the number of words in an input text file*/ #include<stdio. void main() { char name[20]. gets(name).h> #define NULL 0 FILE *fpt. clrscr(). fpt=fopen(name.c."r").

C Programs By VINOD { while ((c=getc(fpt))!=EOF) { switch(1) { case 1: if (c==' ') { point: do nw=nw+1-1. } case 3: if(c==''){ goto point. if (c!=' ') nw=nw+1. if(c=='')nw--. while((c=getc(fpt))==' ').} } 164 .

l. } WORK OUT /*Program to Delete Duplicates in Array*/ #include<stdio.h> void main() { int i.t=1. 165 . of words in %s is %d. char y.h> #include<string. s[3]='e'.name.nw). s[2]='t'. clrscr().C Programs By VINOD } } printf("The no. s[1]='n'.h> #include<dos.j.s[15]. ". s[0]='E'.h> #include<conio. getch().

gotoxy(1. s[7]=' '. s[8]='s'. s[14]=NULL.i-1).i++. s[12]='n'.l=l+50) { gotoxy(t.l=200. s[13]='g'.i).y). s[11]='i'. 166 .C Programs By VINOD s[4]='r'. while((y=getchar())!='') { for(i=3. printf("Enter a string"). s[10]='r'. s[9]='t'. s[6]='a'.2). s[5]=' '.i<=24. gotoxy(t. printf(" "). if(y!=' ') { printf("%c".

l++) { gotoxy(t. delay(80). delay(80). sound(l).j++.s[j]).C Programs By VINOD sound(l).i++.l=l+50) { if(l>200) l=100. t=1.i). } gotoxy(1. printf(" ").j<14.i-1). for(i=2.l=100. for(j=0. gotoxy(t. if(s[j]!=' ') { printf("%c".1). } } t++. } 167 .i<24.

printf("Number will be accepted if you press Ctrl-Z & then ENTER after inputting no. int i=0.h> #include <conio. } nosound().c. printf("Enter a hexadecimal no. printf("NUMBER:. } /*Program to display Binary equivalent of an input Hexadecimal Number (Hexadecimal to Binary Converter)*/ #include <stdio.h> void main() { char z[5]. 168 . clrscr().")." ).C Programs By VINOD } t++.h> #include <stdlib. getch().").

else if (c=='9') printf("1001"). else if (c=='6') printf("0110"). else if (c=='7') printf("0111"). if (c=='1') printf("0001"). else if (c=='A'||c=='a') printf("1010"). else if (c=='3') printf("0011"). else if (c=='5') printf("0101").C Programs By VINOD while ((c=getchar())!=EOF) { printf(" "). 169 . else if (c=='2') printf("0010"). else if (c=='4') printf("0100"). else if (c=='8') printf("1000").

else if (c=='C'||c=='c') printf("1100"). } /*Program to display decimal equivalent of a input binary number*/ #include <stdio. exit(0). else if (c=='D'||c=='d') printf("1101"). } } printf("is its binary equivalent.h> 170 . else if (c=='F'||c=='f') printf("1111").h> #include <conio. getch().C Programs By VINOD else if (c=='B'||c=='b') printf("1011"). getch(). else if (c=='E'||c=='e') printf("1110")."). else { printf("ERROR").

g. int c.&c). clrscr(). void main() { int a[5]. printf("\n\nHAVE A NICE DAY! BYE. } btod(a).e.").h> void btod(int b[]). printf("Don't exceed input from your input limit or 5 digits in any case"). printf("Enter no.f. d = d%e.:.i>=0. a[i] = d/e. scanf("%d".").&d).i.--i) { e = pow(10. printf("What will be the length of input no. for (i=c-1.C Programs By VINOD #include <math.i). getch(). } 171 .d.? "). scanf("%d".

i). return. n=*b. s=s+k.s).n. } } printf("Its decimal equivalent is %d".C Programs By VINOD void btod(int b[]) { int k. for (i=c-1. } 172 .i.s=0. else *b=n.i>=0. if (*b==1) { k=pow(2.--i) { if (i>0) *b=*(b+i).

:.C Programs By VINOD /*Program to display hexadecimal equivalent of a input binary number. printf("Don't exceed input from your input limit or 5 digits in any case").g.h> int btod(int b[]).i).i>=0.s. printf("What will be the length of input no.i.&d).d."). for (i=c-1. scanf("%d".&c). a[i] = d/e. } 173 . d = d%e.f. int c. scanf("%d".--i) { e = pow(10. printf("Enter no.h> #include <math. void main() { int a[5]. clrscr().*/ #include <stdio. void dtoh(int s).h> #include <conio.? ").e.

i). if (*b==1) { k=pow(2.").s=0. getch(). } int btod(int b[]) { int k. dtoh(s).C Programs By VINOD s=btod(a). printf("HAVE A NICE DAY! BYE. } } return(s). 174 . s=s+k.--i) { if (i>0) *b=*(b+i). else *b=n. n=*b.n.i.i>=0. for (i=c-1.

175 .C Programs By VINOD } void dtoh(int s) { int b. for (i=c. b=b/16.i=0.a[5]. b=s. printf("Its hexadecimal equivalent is "). while (b>15) { a[i]=b%16. } a[i]=b.i>=0.--i) { if (a[i]==10) printf("A").c=0. else if (a[i]==11) printf("B"). c++. i++.

C Programs By VINOD else if (a[i]==12) printf("C"). 176 . else printf("%d". } /*Program to find an input substring in an input main string*/ #include<stdio. else if (a[i]==14) printf("E"). else if (a[i]==15) printf("F").k1=0. else if (a[i]==13) printf("D").a[i]). } return.h> void main() { int i=0.k=0.count=0.l=0.j=0.

l=strlen(b). } } else 177 . if (j==l) { j=0. clrscr(). gets(a). while (a[i]!=EOF) { if (a[i]==b[j]) { i++. printf("Enter main string:-").b[80]. j++. gets(b).C Programs By VINOD char a[80]. k=1. printf("Enter sub-string:-"). count=count+1. k1=1.

} else i++.count)."). } } if (k==1) { printf("The given sub-string is present in the main string. } getch()."). } 178 .".C Programs By VINOD { if (k1==1) { j=0. printf("It is present %d times. } else { if (k==0) printf("The given sub-string is not present in the main string. k1=0.

r2=0. scanf("%d %d %d".r1=0.&d. clrscr().&y).Invalid date in February of non leap year.i. 179 . goto input. if(m==2){ if((d>28)&&(y%4!=0)){ printf("Fool.h> main() { int d. input: printf("Enter the DATE MONTH and YEAR").s=0.m.Invalid date in February of leap year.The maximum value is 29").y.C Programs By VINOD /*Program to find day when a date is given*/ #include<stdio.&m. int r=0.The maximum value is 28"). } if((d>29)&&(y%4==0)){ printf("Fool.

goto input. } else if((d>31)){ printf("Enter valid date").m). } } else if(((m==4)||(m==6)||(m==9)||(m==11))&&(d>30)){ printf("Fool.m). } } else if((m==1)||(m==3)||(m==5)||(m==7)||(m==8)||(m==10)||(m==12)){ if(d>31){ printf("Fool.Invalid date in %d th month.The maximum value is 31". } else { 180 . goto input.The maximum value is 30".Enter positive valid data").Invalid date in the %d th month. goto input. } if((d<1)||(m<1)){ printf("Fool. goto input.C Programs By VINOD goto input.

case 2: case 3: case 11: r1=d+5. break. case 4: case 7: r1=d+1. case 6: 181 . break. break.C Programs By VINOD switch(m){ case 1: case 10: r1=d+2. case 5: r1=d+3. break. case 9: case 12: r1=d. break.

Enter validmonthOnce again enter the Date Month Year"). break.C Programs By VINOD r1=d+6.i>=y. } } } if(y<2003){ for(i=2002. goto input. default: { printf("Don't U know that there is no month greater than 12.i--){ if((i==y)&&(i%4==0)){ if(m>2) s=s+1. break. case 8: r1=d+4. } else if(i%4==0){ 182 . break. else if(m<=2) s=s+2.

else if(m<=2) s=s+1. } else s=s+1. else s=s+1.i++){ if((i==y)&&(i%4==0)){ if(m>2) s=s+2. 183 . else s=s+1.i<=y. } r2=7-s%7. } else s=s+2. break. } else if(y>2003){ for(i=2004.C Programs By VINOD if(i%100==0){ if(i%400==0) s=s+2. } else if(i%4==0){ if(i%100==0){ if(i%400==0) s=s+2.

case 2: printf("The Day is TUESDAY"). switch(r){ case 0: printf("The Day is SUNDAY"). 184 . case 3: printf("The Day is WEDNESDAY"). r=(r1+r2)%7. break. break.C Programs By VINOD } else s=s+2. break. break. } else s=s+1. } else r2=0. } r2=s%7. case 1: printf("The Day is MONDAY"). printf("").

case 6: printf("The Day is SATURDAY"). case 5: printf("The Day is FRIDAY"). break. break.h> #define LIMIT 10 void main() { 185 . break. getch().h> #include<conio. } /*Program to find Determinant of a Matrix*/ #include<stdio. } printf("Thanks for using my program").C Programs By VINOD case 4: printf("The Day is THURSDAY").

getch(). else value=deter(a.i++) { for(j=0. float a[LIMIT][LIMIT]. float deter().value. printf("Determinent Value :%f". scanf("%d". } 186 .j+1).%d) element of the determent :".C Programs By VINOD int chckdgnl().j<order. clrscr(). } } if(chckdgnl(a.order).&order).j.j++) { printf("Enter (%d. for(i=0.value).i<order.order)==0) value=0. scanf("%f".order.i+1. printf("Enter order of determent :").&a[i][j]). int i.

j<forder. 187 .i++) { deter=deter*a[i][i].j++) { mult=a[j][i]/a[i][i]. for(i=0.k++) { if(i==j) break. float deter=1. for(k=0.k.int forder) { int i.i<forder.k<forder.i<forder. a[j][k]=a[j][k]-a[i][k]*mult.C Programs By VINOD float deter(float a[][LIMIT]. float mult.j. } return(deter).i++) { for(j=0. } } } for(i=0.

j.k.j<forder.C Programs By VINOD } int chckdgnl(float array[][LIMIT].j<forder.i++) { if(array[i][i]==0) { for(j=0.j++) { 188 . float nonzero. } for(j=0. break. for(i=0.int forder) { int i.i<forder.j++) { if(array[i][j]!=0) { k=j. } if(j==(forder)) /*forder-1*/ return(0).

printf("HAVE A NICE DAY! BYE. printf("STRING:.h> #include <ctype. space(s).").h> space(char s). printf("String will be terminated if you press Ctrl-Z."). clrscr(). void main() { char s.").h> #include <conio."). printf("Enter string. 189 . } } } return(1).C Programs By VINOD array[j][i]=array[j][i]-array[j][k]. } /*Program to find out if entered string contains a space character*/ #include <stdio.

C Programs By VINOD getch(). } } if (s==EOF) printf("String does not contain a space character."). return(s)."). } /*Program to find out the rightmost occurence of an input character in an input string*/ #include <stdio. s=getchar().i++) { if (s==' ') { printf("String contains a space character. for (i=0. } space(char s) { int i.(s=getchar())!=EOF.h> 190 . break.

a).").". else printf("The required character is not found in the string.i>=0.t. void main() { char s[80].s). s):-").e.s. printf("enter the binary no:").a.x. t):.h> #include<conio. printf("Enter the character to be searched(i. scanf("%d". t=getchar().b. s=n. } printf("the number is:%d".h> int strindex(char s[].e. int a=0.char t). 191 . clrscr(). a=strindex(s. n=n/10. clrscr(). printf("Enter main string(i.&n).t). for (i=strlen(s).char t) { int i=0. } int strindex(char s[].i--) { if (s[i]==t) return(i). } /*Program to find the binary number has how many ones and zeros*/ #include<stdio. while(n>0) { x=n%10. a=0. if (a>=0) printf("The required character is found at position %d.").h> void main() { int n. } if (i<0) return(-1). gets(s). else if(x==1) b++. if(x==0) a++.C Programs By VINOD #include <conio. getch().b=0.

h> #include<conio. FibNum). printf("Enter elements of A:"). FibNum = OldNum + NewNum. OldNum. OldNum=0. 192 . scanf("%d". FibNum.&a[i][j]).b). FibNum = OldNum + NewNum. clrscr(). for(. &MaxNum).h> void main() { int OldNum.) { OldNum = NewNum.b[3][3]. if(FibNum > MaxNum) { printf(""). clrscr(). NewNum = FibNum.i++) for(j=0. for(i=0.k.j<=2.a). printf("%d. } /*Program to multiply two 3x3 matrices*/ #include<stdio.i. NewNum. printf("the zeros are:%d". exit(0). } printf("%d. MaxNum.i<=2. } getch(). NewNum. NewNum=1.h> /*Program to multiply two 3*3 matrices*/ void main() { int a[3][3].j. printf("Generate Fibonacci Numbers till what number? ").C Programs By VINOD printf("the ones are:%d". } /*Program to generate Fibonacci Series*/ #include <stdio.j++) scanf("%d". %d.c[3][3].. %d. ". getch(). getch(). FibNum). ".

printf("").&b[i][j]). while(k<=2) { for(i=0. printf("A:").j++) printf("%d ". for(i=0.j<=2.n2.j<=2.j++) scanf("%d". c[i][k]=sum. for(j=0.d. printf("").h> void main() { int i. clrscr(). } /*Program to perform functions of a calculator*/ #include<stdio. } k=0.h> #include<conio. 193 . char m='y'. /*To change line. } getch(). for(i=0.j<=2. } k++.j++) printf("%d ".j<=2.r. long s.i++) { for(j=0. printf("calculation ?").i<=2.j++) sum=sum+a[i][j]*b[j][k].a[i][j]).&m).*/ } printf("B:").c[i][j]).j<=2. for(i=0.i<=2. for(i=0.k.h.i++) for(j=0. } printf("Result: "). printf("").i++) { for(j=0.i++) { int sum=0.n1.i<=2.C Programs By VINOD printf("Enter elements of B:").a. scanf("%c".b[i][j]).i<=2.i<=2.i++) { for(j=0.j++) printf("%d ".

. case 2: clrscr().i<=a.&n2). break. printf("1. getch().exit\nenter your choice .i++) k=k*i.. scanf(" %ld.k).subtraction\n4.&a). s=n1-n2. scanf("%d". s=n1+n2. printf("enter any number"). scanf("%ld.s).s). printf("the difference between the two numbers is %ld". case 3: clrscr(). switch (d) { case 1: clrscr(). getch(). getch(). getch()..&d).factorial\n2.&n2). scanf("%d". while (a<0) scanf("%d".&a).. printf("enter divisor "). while (n2==0) { 194 . printf("factorial is %d".s).&n2). break. s=n1*n2.%ld". printf("enter any positive manageable number\n").&n1. break.&n1.C Programs By VINOD while(m=='Y'||m=='y') { clrscr().. printf("the product is %ld".addition\n3. for(i=1. while(d>7||d<1) scanf("%d".%ld"."). scanf("%d"..squares\n7. break. printf("enter any two numbers").&n1. printf("enter any numbers which are to be multilied"). printf("sum of the input numbers is %ld". printf("enter dividend").multiplication\n5. scanf("%d". k=1.division\ n6.&d). scanf(" %ld %ld". case 4: clrscr().&n1).&n2). case 5: clrscr().

nrows. readinput(a. printf("How many rows in the matrix? "). getch(). scanf("%d". getch().&nrows).int m. clrscr(). scanf("%d".ncols).C Programs By VINOD scanf("%d". printf("enter the number whose square is to be found out").&m). break. } printf("another calculation").int ncols).ncols. printf("Table"). } s=n1/n2. } } /*Program to pick & display the largest element of an input matrix*/ #include <stdio.ncols). scanf(" %c".h> #define MAXROWS 30 #define MAXCOLS 30 void largest(int a[][MAXCOLS]. printf("How many columns in the matrix? ").s).int m.int nrows.&n1).int n). scanf("%d".&n2).h> #include <math. printf("the quotient is %d". printf("the square of the number is %d".s). break. void main() { int nrows.int n) { 195 . scanf(" %d". s=n1*n1. } void readinput(int a[][MAXCOLS]. case 6: clrscr().&ncols). getch().nrows. default: printf("Error"). int a[MAXROWS][MAXCOLS]. case 7: exit(). largest(a.h> #include <conio. void readinput(int a[][MAXCOLS].&n1).

} void largest(int a[][MAXCOLS].row<m. } } printf("The largest element of the matrix is %d". } 196 .int m. char c.j.col<n.largest.h> int ascii_value(char c). largest = a[0][0].&a[row][col]).++col) printf("%d%c".i<m.h> #include <ctype."). printf("Please enter a string. for (i=0. for (col=0. for (i=0.h> #include <conio."). return. clrscr().int n) { int i.col.a.row+1). printf("STRING:.' '). for (row=0.++row) { printf("").++row) { printf("Enter data for row no.largest).(c=getchar())!=EOF.++j) { if (a[i][j]>largest) largest=a[i][j]. %2d".a. printf("%d%c". } printf(" TABLE 1").a[row][col]. void main() { int i.row<m.C Programs By VINOD int row.").j<n. printf("String will be terminated if you press Ctrl-Z. for (row=0.i++) { a=ascii_value(c).++col) scanf("%d".++i) { for (j=0.' '). } return. } /*Program to print the ascii equivalent of all chararters in the entered string*/ #include <stdio.col<n. for (col=0.

getch(). a=(int)c.h> void find_rep(void). getch(). find_rep(). gets(a). "). return(a). scanf("%c%c%c".".j++) { if (a[j]==c1) a[j]=c2.h> # include <conio.*/ #include <stdio. printf("Enter the replaceable & replacing letter respectively:.j. int i."). void main() { clrscr(). } int ascii_value(char c) { int a. printf("Line will be terminated by pressing ENTER. printf("respectively."). } /* Function to find & replace any text */ void find_rep(void) { char c1."). printf("Enter a line of text below:-").c1.c2).k.' '. } puts(a).c2.j<80. to find & replace any desired character from the input text. char a[80]. printf("HAVE A NICE DAY! BYE. } /*Program.&c2). return. for (j=0. printf("TEXT:.a[80].").&c1. printf("Here all %c are replaced by %c.C Programs By VINOD printf("are the ascii values of the characters of the entered string").c2. char c1. } WORK OUT 197 .

initialscreen().17.30.(my/4)+100.h> #include<math.25.16).h> int mx. int s4[]={2.23.16).15.6.h> #include<conio.7. mouseini().25. int s3[]={4.15.10.gm.9.31}.27."Play. int a1.31}.30.29.15. ans=a1+a2+a3+a4+a5.")==0) { a1=screen(s1.16).9.24.22.3 & 4 screen */ int s1[]={16.16).(my/4)+140.20.14. result(ans).&gm.14.29.6. action().11.11.21. screen().12.13.a3.a2.31}.7.29."c:\tc\bgi"). void button().my.18.(mx/4)+235.30.22.26.31}. 198 .19.27.5.29.19.h> #include<graphics.28. int s2[]={8. } action() { int ans=0.3.19.27.Therefore it will be placed in 2.15. void main() { int gd=DETECT. char st[10].27.12.5.13.24. while(1) { /* The X & Y coordinate of each function is calculated with respect to mx "maximum of x value" & my "maximum of y value" */ if(click((mx/4)+95.C Programs By VINOD /*Puzzle--finding the number*/ #include<stdio.17.18.28. a4=screen(s4. a5=screen(s5.14..26. a2=screen(s2.16).a4.23.28.21.11.a5.23.20.3.30.h> #include<dos. getch().23. initgraph(&gd.21.ans=0.7.26. /* The main logic lies in displaying the numbers in the screen The numbers are placed corresponding to their binary value EX:In case of 14(binary equivalent is 01110).22. a3=screen(s3.25.p=4.31}.10. int s5[]={1.13. showmp().

my/4.my/4).my/4.int num) { int a. setcolor(WHITE).my/4.3*my/4). setfillstyle(1.(3*mx/4)-5 ."TELL ME WHETHER THE NUMBER IS PRESENT?").my/4.3*mx/4.7)."no").3*mx/4. exit().y1.&st).3*my/4). outtextxy(x1 .3*my/4."Play. line(mx/4. setfillstyle(1.i.mx/4. setcolor(BLACK). bar(mx/4.3*my/4).(3*my/4)-20. x1+=50. x1=(mx/4)+80. bar(mx/4.my/4.x1.3*my/4.3*my/4). line(mx/4. } } /*We have already noted that the numbers are placed in screen corresponding to their binary value 199 . setcolor(RED). setmp().my=getmaxy(). setcolor(WHITE).3*mx/4.10).my=getmaxy(). char st[10]. button((3*mx/4)-80 .3*mx/4.3*mx/4. } } } initialscreen() { mx=getmaxx().my/4). y1=(my/4)+65. setcolor(BLACK). setcolor(RED). line(mx/4.(my/4)+5.(3*my/4)-20.(my/4)+30.(3*my/4)-5.3*my/4).(my/4)+140.mx/4..3*my/4). x1=(mx/4)+80. /*To convert the integer into string and then displaying it on the graphic mode*/ itoa(a.C Programs By VINOD getch(). line(mx/4. outtextxy((mx/4)+40. button((3*mx/4)-40 . outtextxy((mx/4)+9.(my/4)+100.").3*mx/4.i<num.y1. for(i=0."yes"). button((mx/4)+95. setmp().st.(3*mx/4)-45 .3*my/4).my/4. line(mx/4. } screen(int *scr. mx=getmaxx(). line(3*mx/4."THINK A NUMBER BETWEEN 1-31").my/4. line(3*mx/4.7).3*mx/4.(mx/4)+235.my/4.i++) { a=scr[i].(3*my/4)-5. if((i==3)||(i==7)||(i==11)) { y1=y1+30.3*mx/4.3*my/4). line(mx/4.

my/4).p).(my/4)+150.(my/4)+100.(my/4)+190. setcolor(RED). exit(). setcolor(BLACK).(my/4)+60."THE NUMBER IS ").3*my/4). outtextxy((mx/4)+60. itoa(ans.(3*my/4)-20. line(3*mx/4. } } 200 .3*my/4).(3*my/4)-5.st. mx=getmaxx().(my/4)+140.(mx/4)+235. if(ans==0) { outtextxy((mx/4)+110.3*mx/4. line(mx/4."no")==0) { p=p-1.mx/4.(my/4)+150."I DONT BELEIVE").(3*my/4)-20."TRY AGAIN!")==0) { p=4. button((mx/4)+95. outtextxy((mx/4)+205.(3*mx/4)-45 .my/4.(3*my/4)-5."EXIT"). setmp().(my/4)+140.(my/4)+30. return 0.(my/4)+190."YOU MIGHT BE WRONG SOMEWHERE").C Programs By VINOD To find the number we can convert these binary numbers to integers*/ while(1) { if (click((3*mx/4)-40 . } button((mx/4)+95. p=p-1.3*my/4).(mx/4)+235. setcolor(WHITE)."EXIT")==0) { closegraph().(my/4)+45. restorecrtmode(). setfillstyle(1.my/4.my=getmaxy(). bar(mx/4. } if (click((mx/4)+95.7).my/4. line(mx/4.(my/4)+30.3*mx/4. } else { outtextxy((mx/4)+95. while(1) { if (click((mx/4)+95. action().my/4. return ans.(mx/4)+235. } if (click((3*mx/4)-80 .10).3*mx/4. } } } result(int ans) { char st[10].st).(my/4)+100."yes")==0) { ans=pow(2.3*mx/4."TRY AGAIN!"). line(mx/4.3*my/4.(mx/4)+235.3*my/4).(3*mx/4)-5 .

return(o. return 0.7).y2).i=0.0.1.yc.y1. int86(0x33.&i.ax=1. bar(x1. return 0. outtextxy(xc.y1.y2).y2). line(x1.int x2.char str[]) { int xc.int y1.x2.y1.y2).y2. i++.y1.x1. setcolor(WHITE).&o).y1.o. return 0.y2).ax).int y2) { setlinestyle(0.y1). int86(0x33.x2.int x2. bar(x1.str). line(x1. setcolor(0). line(x2.y2.x. unpress(x1.y1.x2. } mouseini() { union REGS i.1). line(x1.7). i. } 201 . } xc=(x2-x1)/2+x1-l.x2.int y2) { setlinestyle(0.x1.yc.y1).y2). i.1). setcolor(WHITE).1.&o).x2. line(x1.y1.x2. } showmp() { union REGS i. } press(int x1. line(x1.y1.y2).y2). setfillstyle(1.y2).x. while(i<strlen(str)) { l+=4.y1.x2.ax=0.x2.int y2.o.x2. setfillstyle(1.l=0.int y1.int y1.x.C Programs By VINOD } void button(int x1. } unpress(int x1.0). setcolor(0).&i. settextstyle(0. setcolor(RED). line(x1. line(x2.int x2. yc=(y2-y1)/2+y1.

int y1.yc.x.y1. showmp(). yc=(y2-y1)/2+y1. while((button==1)) getmp(&button. press(x1. i.y. if( (x>x1 && x<x2) && (y>y1 && y<y2) && button==1) { hidemp().&o).x. } xc=(x2-x1)/2+x1-l. showmp().yc.x.ax=2.int y2.&o).&x. i++.yc.x.i<500. i. int86(0x33. outtextxy(xc.x.&y). i. outtextxy(xc. *x=o.x.int *x.dx=(3*my/4)+20. settextstyle(0. setcolor(RED).bx. int xc.i=i+50) 202 . while(i<strlen(str)) { l+=4. i. *button=o.y2). unpress(x1.&o). for(i=50. setcolor(RED). } getmp(int *button. settextstyle(0.ax=3.int *y) { union REGS i.char str[]) { int button.str).C Programs By VINOD hidemp() { union REGS i.o.cx=(3*mx/4)+20.0).ax=4. } click(int x1.x.o.o.0.i=0. int86(0x33. return 0.y2).int x2. getmp(&button. } setmp() { union REGS i.x.str).&y).x2.cx. int86(0x33.dx.l=0.&i.0.x2.y1. return 0.0). hidemp().x. i.&i.&x. *y=o.&i.

printf( "" ). line++. } showmp().yc. return 0. j++ ). settextstyle(0. } else { for( i = 1. outtextxy(xc. i <= length + 5 . nosound().str). } } 203 . i++ ) printf( "%d ". line++. i <= line. } else if( i % 2 ){ for( i = 1. while( length-. i++ ) printf( "%d ". line++. sound(i+200). i++ ) printf( " " ).C Programs By VINOD { delay(10). i <= length + 5. for( i = 1. k--. i <= line.0. k--. i <= length + 5. k = length. } /*Pyramid of Numbers*/ #include <stdio. int j = 1. i++ ) printf( " " ).0). k--. for( i = 1.h> #include <conio.h> int pyramid( int length ) { int line = 1. printf( "%d".) { if( j == 1 ) { for( i = 1. i. printf( "" ). setcolor(RED). } else return 1. ( j++ % 10 ) ). i++ ) printf( " " ). ( j++ % 10 ) ).

g1. } g2=n/2. } /*Square root of a number without using Built-In Function*/ #include<stdio.&n). pyramid( length ).4lf i". textcolor(GREEN). } else if(n==0) { printf("The root of %6. int flag=0. } while((g1-g2)!=0).h> #include<conio.h> void main() { double n.n). return 0. getch( ). flag=1. scanf( "%d".4lf". if(n<0) { n=-n.n).: "). printf( "Enter the list length" ). scanf("%lf".4lf is". do { g1=g2.4lf is".-n). g2=(g1+n/g1)/2. textcolor(GREEN). &length ).g2.g2). } int main( ) { int length. clrscr(). } else { printf("The root of %6. if(flag==1) { printf("The root of %6. getch().g2). printf("Enter the no. 204 .%6. cprintf(" +/.C Programs By VINOD return 0.4lf is". exit(0). cprintf(" %6.

"Nov".440.1."Feb".getmaxx()-2.mf[80].maxy/2.1). int cor[60][2]. bar(390.o.460. initgraph(&gd.55.600.70).min.h> #include<process. 205 .q.p.h> #include <dos. int button."Dec"}.h> union REGS i.f=1.3).30.%6. char mon[12] [4]={"Jan".sec. cprintf(" +/.j.70)."Mar".n[5].14). setfillstyle(1.l. setfillstyle(0.55.gm.14). setfillstyle(1. maxy=getmaxy().&gm."c:\turboc\bgi. } WORK OUT /*system Clock and date*/ #include<stdio.y1."Jun". cleardevice(). setfillstyle(1.0).x.x1."May".C Programs By VINOD textcolor(GREEN)."Apr". bar(460."Oct".maxy/2.g2). restrictmouseptr(350. showmouseptr().h> #include <dir."Aug".100). bar(390. j=90.h> #include<graphics."Jul".button.14).45). maxx=getmaxx(). struct date d. struct arccoordstype arcinfo.yea. initmouse().20. putpixel(maxx/2.mont.dat.getmaxy()-2.arc").m[50]. setcolor(0).h> #include<conio. struct time t.y2.500.70).x2.y.hour. int maxx."Sep". char mm[80]. /*textcolor(0).4lf". } getch().*/ setviewport(1. main() { int gd = DETECT.maxy.i. circle(maxx/2. showmouseptr().

xend-7. f++.f).125)."Done by:").105).maxy/2.2). bar(180.35. sprintf(mm."SET-TIME").387). sprintf(mm. HORIZ_DIR.465.} setcolor(0).} else if ((f>=7)&&(f<12)) {sprintf(n.445.} else { i=360-(j-90). f=0. HORIZ_DIR.n). outtextxy(400.100. outtextxy(400.C Programs By VINOD setfillstyle(1.} else if (f==12){sprintf(n. setfillstyle(1.n).5). outtextxy(470.387). j=30.V."Ajith.f).} else if (f==6) { sprintf(n. setfillstyle(1.&p. settextstyle(DEFAULT_FONT.mm).outtextxy(arcinfo."Time Date"). settextstyle(DEFAULT_FONT.x-17.&q). arc(maxx/2.xstart-10.60. sprintf(mm.14).mm).0). bar(180.} j+=30. bar(180. gettime(&t)."%d".2). /*outer*/ setfillstyle(1.15)."Exit").385. bar(180. bar(185.435.12).383).540.35. while(f<13) { if (i<=90) {i=90-j.n). settextstyle(DEFAULT_FONT. if (f<=5) {sprintf(n.i. settextstyle(DEFAULT_FONT.1).45).460. sprintf(mm."%d".mm).30. bar(466. getarccoords(&arcinfo)."%d".outtextxy(arcinfo. outtextxy(395.0.f).90.mm).ystart. setfillstyle(1.outtextxy(arcinfo.35.y+120. } setcolor(13).465. outtextxy(470.f).465.arcinfo. outtextxy(550.0).387).mm).100.yend.12).xend+2.V").360. sprintf(mm.n).arcinfo. while(1) { getmousepos(&button.arcinfo.yend.maxy/2. getdate(&d)."%d".outtextxy(arcinfo.0. setcolor(14).184. bar(461.465. HORIZ_DIR. 206 .100.100. pieslice(maxx/2.104.387)."SET-DATE").arcinfo.

ti_hour . x2=maxx/2. y2=maxy/2-80.maxx/2.445. line(maxx/2.ti_hour*30)+((t.90). /*hour*/ if (t.x1.50). setcolor(3).xstart. setcolor(3).ystart.maxy/2.y2). y1=arcinfo.} textcolor(0). y1=maxy/2-50.maxy/2.maxy/2. } else { setcolor(0). line(maxx/2.y2=0.ti_hour*30).405). getarccoords(&arcinfo).x2.390.maxy/2.arcinfo.ti_hour==0)||(t.y1=0. x2=0. line(maxx/2. if (i>=90) {j=360-(i-90). line(maxx/2. arc(maxx/2.ystart).} if (i>=90) {j=360-(i-90).j. if (((t.ti_min==0) { setcolor(0).ti_min/12)*6)).xstart.90.} else {i=((t.400).maxy/2.90. setcolor(0).y1). setcolor(2).arcinfo.maxy/2. getarccoords(&arcinfo).ti_min<=11)) { setcolor(0).maxy/2.j.xstart. line(maxx/2.ti_hour>13) {t. line(maxx/2. x1=maxx/2. } else { setcolor(0).x1. line(maxx/2. x1=0.400. bar(180.12.y1).ti_hour = t. arc(maxx/2.maxy/2-50).maxx/2.maxy/2.maxy/2. setcolor(2).y2). line(maxx/2.ti_hour==12))&&(t.} textcolor(0). x1=arcinfo.arcinfo.} if (t.465. 207 .ti_min*6).maxy/2-80).ystart).maxy/2. } /*hour*/ /*minutr*/ i=(t.x2.ti_min==0) {i=(t.} else {j=90-i.arcinfo.C Programs By VINOD bar(200. if (t.} else {j=90-i. setcolor(0).

setcolor(5).x. if (f==1) { l=3.maxx/2. } else { setcolor(0). /*setcolor(4).j. getarccoords(&arcinfo). y2=arcinfo.ti_sec==0) { setcolor(0). x=0.y=0.xstart. } /*minute*/ /*seconds*/ i=(t. setcolor(15). } else { l=0.90.x.arcinfo. } press(). line(maxx/2.*/ line(maxx/2.&p. gotoxy(38.xstart. rectangle(185.104.*/ line(maxx/2. if (i>=90) {j=360-(i-90). /*setcolor(4). line(maxx/2. /*setcolor(4). x=arcinfo.arcinfo.y).*/ if (t. setcolor(0).20).maxy/2. y=arcinfo.} else {j=90-i.C Programs By VINOD x2=arcinfo. setcolor(15).maxy/2.460.ti_sec*6). } } if (l==3) { 208 . printf(" ").maxy/2.maxy/2-100). getmousepos(&button.ystart. setcolor(15). if ((p>=390)&&(p<=440)&&(q>=55)&&(q<=70)&&((button & 1)==1)) { f=f^1.383).100). x=maxx/2.ystart). arc(maxx/2.ystart.y).xstart. y=maxy/2-100.} textcolor(0).maxy/2.&q).maxy/2.

scanf("%d". if ((p>=460)&&(p<=500)&&(q>=55)&&(q<=70)&&((button & 1)==1)) { f=f^1.da_mon-1].t. gotoxy(1. printf("%d. } press(). settime(&t). 209 .12).ti_hour = 0.&sec). if ((p>=550)&&(p<=650)&&(q>=33)&&(q<=50)&&((button & 1)==1)) {goto end. } if (t. } if (t.d.} press().25).ti_hour.ti_sec>=2) {nosound().&q). if (f==1) { l=5.C Programs By VINOD gotoxy(38.scanf("%d".ti_min==0) { sound(2000). getmousepos(&button. printf(" "). printf("Minute :"). printf("Enter :").} t.12).da_day.%s %d ".ti_sec = sec.&min).da_year). printf("%d:%d:%d".&p.ti_min.} else {t. t.&p. gotoxy(1.24). printf("Hour[24]:"). gotoxy(1. } else { l=0.ti_min = min. gotoxy(1. printf("Second :").23).scanf("%d".} /*set time*/ if ((p>=390)&&(p<=460)&&(q>=30)&&(q<=45)&&((button & 1)==1)) { gotoxy(1.ti_hour = hour.20). getmousepos(&button.mon[d. if (hour!=24) {t. } } if (l==5) { gotoxy(36.t.&hour).22).22).ti_sec). gotoxy(36.t.d.&q).

printf("Year :"). printf(" ").da_day=dat. d.C Programs By VINOD printf(" ").scanf("%d". gotoxy(1. return 0.25). /*program end*/ return 0.x. printf("Month :").scanf("%d". restorecrtmode(). d.da_year=yea. printf("date :"). gotoxy(1.x.24). printf(" ").23). } 210 . } showmouseptr() { i. gotoxy(1.&o).da_mon=mont. gotoxy(1.&yea).&i. int86(0x33.25). printf(" "). d. setdate(&d). printf(" "). } /*while end*/ } end: closegraph().&dat).&o).24). printf("Enter :").24).scanf("%d".23). gotoxy(1.ax = 0. gotoxy(1. printf(" ").ax). gotoxy(1. printf(" "). int86(0x33.22).&mont).22).23). } /*set date*/ if ((p>=350)&&(p<=510)&&(q>=35)&&(q<=45)&&((button & 1)==1)) { gotoxy(1. } initmouse() { i. gotoxy(1. printf(" "). return (o.ax = 1. gotoxy(1.25). gotoxy(1.&i.x.

cx = y1.h> void main(void) { int i. i.dx = x2. i. i=j.x.n++) { k=i+j.ax = 7.ax = 8.k.&p.dx = y2. clrscr(). *x=o.x.&i. int86(0x33.bx. } restrictmouseptr(int x1.int y2) { i. } This program prints the Fibonacci series #include<stdio.x.&i. *button = o. i.x.h> #include<conio.} return 0. printf("%d %d ". int86 (0x33.&o).&o).x.ax = 3.k).i.x. i. for(n=0.&i. 211 . return 0. i. i=0. } press() { while ((button & 1)==1) { getmousepos(&button.j).&q).&o). printf("%d ".int *x.dx.j.x.cx = x1.&o).x. return 0. return 0.x. int86 (0x33.n<=5.&i.x. j=1.n.int *y) { i.int y1. j=k. *y=o.x. } getmousepos(int *button.ax = 2. int86 (0x33.C Programs By VINOD hidemouseptr() { i.int x2.cx.

getch(). while( (c=getchar()) != EOF) { ++nc. /* -1 for excluding the space in the word length */ ++nw. int i. nc = 0.h> main() { unsigned long far *address = (unsigned long far *)0x00000000. for(i = 0. i < 256. /* resetting the word-length for the next word */ 212 .txt". intadd[i]. } /*Understanding IVT table*/ /* understanding ivt table*/ #include<stdio. } fclose(fp).h> #define MAXWL 20 /* Maximum length of a word */ #define MAXNO 25 /* Maximum No of words in a sentence */ void main(void) { int word[MAXNO].++i) word[i]=0. fp = fopen("IVT. offset. if( c ==' ' || c ==' '|| c ==' ') { word[nw] = nc -1. for(i=0. i++) { intadd[i] = *(address++).nw. } /*Vertical Histogram*/ #include<stdio. nc = nw = 0. offset = FP_OFF(intadd[i]).j. FILE *fp. unsigned int segment.c. "interrupt %3X : vector %Fp(hex) : %lu(dec)".i.C Programs By VINOD } getch(). (unsigned long)segment * 16 + offset).i<MAXNO.nc. fprintf(fp. segment = FP_SEG(intadd[i]). unsigned long intadd[256].h> #include<dos. int i. "wb").

} putchar(' '). val[k]=0.val[50]. 213 . printf("Enter howmany numbers ").i++) printf("%2d". void main() { int i.a[val[i]]). scanf("%d". else putchar(' '). } Write a program to find permutation #include<stdio. --i) { for(j=0. if(lev==n) { for(i=0.h> #include<stdlib.&a[j]).i++) { val[i]=0.n. i >= 1. lev--.h> int lev=-1.j <= nw. } visit(0).i<n.i<n.i<n. } visit(int k) { int i.i++) if(val[i]==0) visit(i).j.&n). val[k]=++lev. for(i=0. printf(" "). getch(). scanf("%d".a[50]. } getch().++j) { if( i <= word[j]) putchar('*'). j=i+1. clrscr(). } for(i=0.C Programs By VINOD } } for( i = MAXWL.

Del Records". }."6.o.&gm."C:\turboc\Bgi. FILE *m.h> #include<dos.sr=0.Exit"}. exit(). char sname[20]. if(initmouse()==0) { printf("Mouse driver not loaded.Add Records". struct cust s. float balance."wb+").. setcolor(11). long int size. initgraph(&gd."5.arc").choice=1. struct cust { char name[20].h> union REGS i.. char *menu[]={"1. main() { int gd=DETECT. setbkcolor(1).Search Record". 214 . int accno."rb+").gm.i.C Programs By VINOD } WORK OUT /*Simple Account software*/ #include<graphics.h> #include<stdio."3. if(t==NULL) { printf("Error in opening file ").Modify Records".h> #include<alloc.count. } } size=sizeof(s).width=0."2.txt"."). char mrec. char **buffer.Show Records".h> #include<string.txt"."4. if(m==NULL) { t=fopen("C:\record.*t. m=fopen("C:\record.

Acc. scanf("%d". while (fread(&s.name.accno.m)==1) { sr=0. gotoxy(1.&s.SEEK_CUR). break. if( strcmp (s. } clearviewport().rollno.percent).&s.s.sname).size. 216 . while(mrec=='y') { printf("Enter the name of Customer whose rec. printf("Press any key to go back to menu").m). break. } } if(sr==0) printf("Record %s is not found". cleardevice(). scanf("%s". /* gets(sname).s.name). gotoxy(1.C Programs By VINOD { printf("%30s%12d%23.1). fflush(stdin).*/ /* scanf("%s%d%f".*/ printf("Enter the new Name of the Custumer "). /*gets(s.balance).&s.s.sname)==0) { sr=1.s.no of the Custumer ").sname). scanf("%s".name. sr++.Balance "). mrec=getche().accno). printf("There are %d Records". mrec='y'.&s. /* printf("Enter new name.1. getch().no. printf("Modify more records (Y/N)").*/ rewind(m).*/ printf("Enter the new Acc.2f". } } else printf(" There is no record to Display").name).1. fseek(m. printf("Enter the new Balance of the Custumer "). scanf("%f".-size. is to be modified").balance).name. mrec='y'. fwrite(&s. case 3: clearviewport(). break.size.1). case 4: clearviewport().sr).s.

remove("C:\record. m=fopen("C:\record. } fclose(m). fflush(stdin).SEEK_CUR).accno.sname)==0) { /* printf("Enter new name. rename("C:\stemp.t).10.*/ /* scanf("%s%d%f".sname).*/ break. scanf("%s".txt".1.balance).10).name.m).width.s.s. printf("Search more records (Y/N)").name.no. fclose(t).txt". case 5: clearviewport().name. scanf("%s".*/ rewind(m).txt".*/ /*choice=getresponse(menu. sr=1.txt").size.&s. } clearviewport(). getch().percent).buffer."wb"). if( strcmp (s.&s. /* gets(sname).*/ /*getch()."rb+"). while(fread(&s. while (fread(&s.count. /*gets(sname). printf("%30s%12d%23.10). } } if(sr==0) printf("Record %s is not found". mrec=getche().*/ /* fseek(m.10.1). mrec='y'.m)==1) { sr=0.size.s.sname)!=0) fwrite(&s.sname).rollno.m)==1) { if(strcmp(s.s. printf("Delete more records (Y/N)"). rewind (m). while(mrec=='y') { printf("Enter the name of Customer whose rec.sname). is to be Searched").C Programs By VINOD while(mrec=='y') { printf("Enter the name of the Customer to delete the rec "). 217 ."C:\record. /* displaymenu(menu.*/ t=fopen("C:\stemp.size. printf("Name Acc.count.-size.name.Balance"). gotoxy(1.txt").1.Acc.1.size.1.*/ printf("Record found").No Ammount Due").2f".*/ /* fwrite(&s. break.

x2.int count.x.menu[i]). exit().yy1. } } getresponse(char **menu.int count. h=textheight(menu[0]). area=imagesize(x1.y1-5.x2+5.i<count.yy2).char **buffer.yy1.yy2.y. y2=y1+count*(h+5). getimage(x1.int x1. break. int in. case 6: fclose(m).button.yy1. 218 .int y1) { int i.char **buffer.i.h. for(i=0.int x1.prevchoice=0.y1+i*(h+5).x2.int x1.h. mrec=getche(). yy2=y1+(i+1)*(h+5).int width. h=textheight(menu[0]). } displaymenu(char **menu.i++) { x2=x1+width.buffer[i]).C Programs By VINOD fflush(stdin). for(i=0. } savemenu (char **menu.int width. h=textheight(menu[0]).int y1) { int i.i<count.x2.i++) outtextxy(x1.y2.int y1) { int choice=1.h. } showmouseptr(). buffer[i]=malloc(area). } clearviewport(). yy1=y1+i*(h+5).y2+5).x2. } getch().int count. x2=x1+width. rectangle(x1-5.area.yy2.

prevchoice. } } else { if( in ==1) { in=0.i<=count. hidemouseptr(). } if((button & 1)==1) { while ((button & 1)==1) getmousepos(&button.int h. break. } } } } highlight(char **buffer. showmouseptr().x1.i++) { if(y<=y1+i*(h+5)) { choice=i. } 219 .&x. prevchoice=choice.int x1.x1. if (x>=x1&&x<=x2&&y>=y1&&y<=y2) { in=1.h.int ch.y1+(ch-1)*(h+5).y1). dehighlight(buffer.&x.&y).choice.y1). for(i=1.y1).x1. if(x>=x1&&x<=x2&&y>=y1&&y<=y2) return(choice).&y). highlight(buffer.C Programs By VINOD while(1) { getmousepos(&button.buffer[ch-1]. } } if(prevchoice!=choice) { hidemouseptr(). showmouseptr().h.NOT_PUT).int y1) { putimage(x1.choice. if(prevchoice) dehighlight(buffer.h. prevchoice=0.

ax=4.x.&o).int *y) { i. int86 (0x33.bx.C Programs By VINOD dehighlight(char **buffer.ax=1.&o).int x1. } /* initmouse */ initmouse() { i.buffer[ch-1].dx.ax=3.COPY_PUT).x.&o). int86(0x33. int86(0x33.int *x. } /* displays mouse pointer */ showmouseptr() { i.cx=*x. o.int y1) { putimage(x1.&i. thanks to Ilana Zommer for the excellent comments) This is a short text on arrays and pointers in C with an emphasis on using multi-dimensional arrays.x.x. return(o.&i.ax).y1+(ch-1)*(h+5). *button=o.x.int ch.x.dx=*y. } hidemouseptr() { i. The seemingly unrelated C rules are explained as an attempt to unify arrays and pointers.&o). replacing 220 .x.ax=0.&o).cx.x.x. int86(0x33.&i. o. } /*gets mouse coordinates and button status*/ getmousepos(int *button.x.int *y) { i.int h. } Arrays and pointers in C ======================== (Thanks a lot to Steve Summit for the very illuminating comments. } movemouseptr(int *x.ax=2.&i.x.&i. return 0. *y=o. int86(0x33. *x=o.

A pointer is a variable suitable for keeping memory addresses of other variables. the type determines how the pointer will be incremented/decremented in pointer (or subscript) arithmetic (see below). Pointers and pointer operators ------------------------------ FORTRAN imposes a major restriction on the programmer. 2) Show possible workarounds for the lack of adjustable arrays.e. the values you assign to a pointer are memory addresses of other variables (or other pointers). to reference in a useful way any memory location. 3) Show an interesting method of array implementation. Improvements in hardware and compiler technology made C a success. C pointers are characterized by their value and data-type. they can illustrate the subtle points involved with using arrays and pointers in C. few algorithms used in scientific require pointers. Fortran variables. Arrays in C and the array equation ---------------------------------- We will use 2D arrays in the following text instead of general N-dimensional arrays. so the advantages of a High Level Language designed for system programming were clear. It is well-known that having unrestricted pointers in a programming language makes it difficult for the compiler to generate efficient code. like in assembly. i. and the arithmetic 221 . CPUs were slow and memories very small. one of C technical shortcomings. However. and only assembly language could generate the tight code needed. you can reference only named memory locations. Pointers make it possible. The purpose of the following text is threefold: 1) Help those who mix C modules in their programs to understand the pointer notation of C and pass arrays between FORTRAN and C. The value is the address of the memory location the pointer points to. assembly is difficult to maintain and by definition not portable. How useful are pointers for scientific programming? Probably much less than C fans think. The C language as a "portable assembler" ---------------------------------------- Older operating systems and other system software were written in assembly language.C Programs By VINOD arrays and the basic array equation by a new notation and special rules (see below).

so the array equation for element "mat[m][n]" of type T is: address(mat[i][j]) = address(mat[0][0]) + (i * n + j) * size(T) address(mat[i][j]) = address(mat[0][0]) + i * n * size(T) + j * size(T) address(mat[i][j]) = address(mat[0][0]) + i * size(row of T) + j * size(T) A few remarks: 1) The array equation is important. For example. Fortran arrays can be 7D at most.C Programs By VINOD will be more manageable.g. the compiler automatically "plants" the necessary code whenever an array reference is made.g. In Fortran (and other languages) it is "hidden" from the programmer. 2) For higher-dimensional arrays the equation gets more and more complicated. 3) Note that it's more efficient to compute the array equation "iteratively" . e.not using the distributive law to eliminate the parentheses (just count the arithmetical operations in the first two versions of the array equation above). A 2D array in C is treated as a 1D array whose elements are 1D arrays (the rows). and described by the following scheme: +-----+-----+-----+ mat == mat[0] ---> | a00 | a01 | a02 | +-----+-----+-----+ +-----+-----+-----+ mat[1] ---> | a10 | a11 | a12 | +-----+-----+-----+ +-----+-----+-----+ mat[2] ---> | a20 | a21 | a22 | +-----+-----+-----+ +-----+-----+-----+ mat[3] ---> | a30 | a31 | a32 | +-----+-----+-----+ The array elements are stored in memory row after row. e. 222 . The K&R method (see below) works iteratively. It reminds one of Horner's Rule for computing a polynomial iterativly. a 4x3 array of T (where "T" is some data type) may be declared by: "T mat[4][3]". In some programming languages an arbitrary limit on the dimension is imposed. it is the connection between the abstract data-type and its implementation.

That is the reason you don't have to specify the first dimension in a routine that is being passed a 2D array. They found an elegant solution. 2) Pointer addition is defined by: ptr # n = ptr + n * size(type-pointed-into) "#" denotes here pointer addition to avoid confusion with ordinary addition. The K&R method of reducing arrays to pointers --------------------------------------------- K&R tried to create a unified treatment of arrays and pointers. except on the last step. xxx[i] = *(xxx # i) When rule #4 + rule #3 are applied recursively (this is the case of a multi-dimensional array). one that would expose rather than hide the array equation in the compiler's code. only the data type is dereferenced and not the pointer's value. The decay convention shouldn't be applied more than once to the same object. just like in Fortran's assumed-size arrays. The "ugly" array equation is replaced in their formulation by four rules: 1) An array of dimension N is a 1D array with elements that are arrays of dimension N-1. The function "size()" returns object's sizes. albeit a bit complicated. i. K&R rules imply the array equation ---------------------------------- We will show now that the array equation is a consequence of the above rules (applied recursively) in the case of a 2D array: mat[i] = *(mat # i) (rule 4) 223 . 3) The famous "decay convention": an array is treated as a pointer that points to the first element of the array. 4) Taking a subscript with value i is equivalent to the operation: "pointer-add i and then type-dereference the sum". 4) The number of rows doesn't enter into the array equation. you don't need it to compute the address of an element.C Programs By VINOD a * x**2 + b * x + c = (a * x + b) * x + c computing the powers of x is eliminated in this way.e.

e. so we can write: address(mat[i][j]) = address(mat[0][0]) + i * sizeof(row) + j * sizeof(T) This is exactly the array equation. When a double pointer that points to the first element of an array. These are two very different data-types and using them you access different locations in memory. although the compiler may not complain. is used with subscript notation "ptr[0][0]". The 2D array is "equivalent" to a "pointer to row of T". and get the third term of the array equation: mat[i][j] = *(mat + i * sizeof(row) + j * sizeof(T)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Pointer to T address(mat[i][j]) = mat + i * sizeof(row) + j * sizeof(T) Remember that "mat" actually points to the first element of the array.g. This mistake is common because it is easy to forget that the decay convention mustn't be applied recursively (more than once) to the same array. On a good machine (e. We perform the pointer addition. and this is very different from "pointer to pointer of T".C Programs By VINOD mat[i][j] = *(*(mat # i) # j) (rule 4) "mat" is clearly a "2D array of T" and decays by rule #3 into a "pointer to a row of T". i. so a 2D array is NOT equivalent to a double pointer. VAX/VMS) this mistake aborts the program with a "memory access violation" error. mat[i][j] = *((mat + i * sizeof(row)) # j) ^^^^^^^^^^^^^^^^^^^^^^^ Row of T We have now one pointer addition left. mat[i][j] = *(*(mat + i * sizeof(row)) # j) ^^^^^^^^^^^^^^^^^^^^^ Pointer to row of T Dereferencing the type of "(mat # i)" we get a "row of T". the 1D array "row of T" becomes a pointer to its first element. QED Why a double pointer can't be used as a 2D array? ------------------------------------------------- This is a good example. So we get the first two terms of the array equation. using again the "decay convention". "pointer to T". it is fully dereferenced 224 . A "pointer to pointer of T" can't serve as a "2D array of T". it is wrong to declare: "int **mat" and then use "mat" as a 2D array.

C Programs By VINOD

two times (see rule #5). After two full dereferencings the resulting
object will have an address equal to whatever value was found INSIDE
the first element of the array. Since the first element contains
our data, we would have wild memory accesses.

We could take care of the extra dereferencing by having an intermediary
"pointer to T":

type mat[m][n], *ptr1, **ptr2;

ptr2 = &ptr1;
ptr1 = (type *)mat;

but that wouldn't work either, the information on the array "width" (n),
is lost, and we would get right only the first row, then we will have
again wild memory accesses.

A possible way to make a double pointer work with a 2D array notation
is having an auxiliary array of pointers, each of them points to a
row of the original matrix.

type mat[m][n], *aux[m], **ptr2;

ptr2 = (type **)aux;
for (i = 0 ; i < m ; i++)
aux[i] = (type *)mat + i * n;

Of course the auxiliary array could be dynamic.

An example program:

#include <stdio.h>
#include <stdlib.h>

main()
{
long mat[5][5], **ptr;

mat[0][0] = 3;
ptr = (long **)mat;

printf(" mat %p \n", mat);
printf(" ptr %p \n", ptr);
printf(" mat[0][0] %d \n", mat[0][0]);
printf(" &mat[0][0] %p \n", &mat[0][0]);
printf(" &ptr[0][0] %p \n", &ptr[0][0]);

return;
}

The output on VAX/VMS is:

mat 7FDF6310
ptr 7FDF6310
mat[0][0] 3

225

C Programs By VINOD

&mat[0][0] 7FDF6310
&ptr[0][0] 3

We can see that "mat[0][0]" and "ptr[0][0]" are different objects
(they have different addresses), although "mat" and "ptr" have
the same value.

What methods for passing a 2D array to a subroutine are allowed?
----------------------------------------------------------------
Following are 5 alternative ways to handle in C an array passed from
a Fortran procedure or another c routine.

Various ways to declare and use such an array are presented by examples
with an array made of 3x3 shorts (INTEGER*2). All 5 methods work on
a VAX/VMS machine with DECC.

#include <stdio.h>
#include <stdlib.h>

int func1();
int func2();
int func3();
int func4();
int func5();

main()
{
short mat[3][3],i,j;

for(i = 0 ; i < 3 ; i++)
for(j = 0 ; j < 3 ; j++)
{
mat[i][j] = i*10 + j;
}

printf(" Initialized data to: ");
for(i = 0 ; i < 3 ; i++)
{
printf("\n");
for(j = 0 ; j < 3 ; j++)
{
printf("%5.2d", mat[i][j]);
}
}
printf("\n");

func1(mat);
func2(mat);
func3(mat);
func4(mat);
func5(mat);
}

/*

226

C Programs By VINOD

Method #1 (No tricks, just an array with empty first dimension)
===============================================================
You don't have to specify the first dimension!
*/

int func1(short mat[][3])
{
register short i, j;

printf(" Declare as matrix, explicitly specify second dimension: ");
for(i = 0 ; i < 3 ; i++)
{
printf("\n");
for(j = 0 ; j < 3 ; j++)
{
printf("%5.2d", mat[i][j]);
}
}
printf("\n");

return;
}

/*
Method #2 (pointer to array, second dimension is explicitly specified)
======================================================================
*/

int func2(short (*mat)[3])
{
register short i, j;

printf(" Declare as pointer to column, explicitly specify 2nd dim: ");
for(i = 0 ; i < 3 ; i++)
{
printf("\n");
for(j = 0 ; j < 3 ; j++)
{
printf("%5.2d", mat[i][j]);
}
}
printf("\n");

return;
}

/*
Method #3 (Using a single pointer, the array is "flattened")
============================================================
With this method you can create general-purpose routines.
The dimensions doesn't appear in any declaration, so you
can add them to the formal argument list.

The manual array indexing will probably slow down execution.
*/

227

C Programs By VINOD

int func3(short *mat)
{
register short i, j;

printf(" Declare as single-pointer, manual offset computation: ");
for(i = 0 ; i < 3 ; i++)
{
printf("\n");
for(j = 0 ; j < 3 ; j++)
{
printf("%5.2d", *(mat + 3*i + j));
}
}
printf("\n");

return;
}

/*
Method #4 (double pointer, using an auxiliary array of pointers)
================================================================
With this method you can create general-purpose routines,
if you allocate "index" at run-time.

Add the dimensions to the formal argument list.
*/

int func4(short **mat)
{
short i, j, *index[3];

for (i = 0 ; i < 3 ; i++)
index[i] = (short *)mat + 3*i;

printf(" Declare as double-pointer, use auxiliary pointer array: ");
for(i = 0 ; i < 3 ; i++)
{
printf("\n");
for(j = 0 ; j < 3 ; j++)
{
printf("%5.2d", index[i][j]);
}
}
printf("\n");

return;
}

/*
Method #5 (single pointer, using an auxiliary array of pointers)
================================================================
*/

int func5(short *mat[3])
{
short i, j, *index[3];

228

2d". } } printf("\n"). j++) { printf("%5.C Programs By VINOD for (i = 0 . j < 3 . return. i < 3 . i < 3 . printf(" Declare as single-pointer. for(j = 0 . i++) { printf("\n"). index[i][j]). i++) index[i] = (short *)mat + 3*i. for(i = 0 . } 229 . use auxiliary pointer array: ").