c programs

163
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> #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); 1

Upload: sandeshcv

Post on 23-Nov-2014

231 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: C Programs

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>#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();1

Page 2: C Programs

C Programs By VINOD

}

Progra to find Gross Salary

#include<stdio.h>#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();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(){

2

Page 3: C Programs

C Programs By VINOD

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++)

sum=sum+i;printf(" 1/%d",n);printf("\nSum=1/%d",sum+1/n);getch();

}

/* true.c -- What are in C the values of TRUE and FALSE? */

#include <stdio.h> int main(void) { printf("The value of 1<2 is %d\n", (1<2)); printf("The value of 2<1 is %d\n", (2<1)); }

/* fibo.c -- It prints out the first N Fibonacci numbers. */

#include <stdio.h>

int main(void) { int n; /* The number of fibonacci numbers we will print */ int i; /* The index of fibonacci number to be printed next */ int current; /* The value of the (i)th fibonacci number */ int next; /* The value of the (i+1)th fibonacci number */ int twoaway; /* The value of the (i+2)th fibonacci number */

printf("How many Fibonacci numbers do you want to compute? "); scanf("%d", &n); if (n<=0) printf("The number should be positive.\n"); else { printf("\n\n\tI \t Fibonacci(I) \n\t=====================\n"); next = current = 1; for (i=1; i<=n; i++) {

3

Page 4: C Programs

C Programs By VINOD

printf("\t%d \t %d\n", i, current);twoaway = current+next;current = next;next = twoaway;

} }}

/* The output from a run of this program was:

How many Fibonacci numbers do you want to compute? 9

I Fibonacci(I) =====================1 12 13 24 35 56 87 138 219 34

*/

A simple example showing some comparison operators

#include <stdio.h> int main(){

int number1 , number2;printf("Enter the number1 number to compare.\n");scanf("%d",&number1);printf("Enter the number2 number to compare.\n");scanf("%d",&number2);printf("number1 > number2 has the value %d\n", number1 > number2);printf("number1 < number2 has the value %d\n", number1 < number2);printf("number1 == number2 has the value %d\n", number1 == number2);return 0;

}

Convert MB to KB

4

Page 5: C Programs

C Programs By VINOD

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

double megabytes , kilobytes;printf("Please enter the amount of megabytes to convert.\n");scanf("%Lf",&megabytes);/*convert megabytes to kilobytes*/kilobytes = megabytes * 1024;/*convert kilobytes to megabytes*//*this is for kilobytes to megabytes*//*megabytes = kilobytes / 1024*/printf("There are %Lf kilobytes in %Lf megabytes.\n",kilobytes,megabytes);

return 0;}

Program to find your Day of Birth given Date of Birth

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

main(){ clrscr(); int d,m,y,year,month,day,i,n; printf("Enter how many times you want to run this program : "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("Enter the date : "); scanf("%d%d%d",&d,&m,&y); if( d>31 || m>12 || (y<1900 || y>=2000) ) { printf("INVALID INPUT"); getch(); exit(0); } year = y-1900; year = year/4; year = year+y-1900; switch(m) { case 1: case 10:

5

Page 6: C Programs

C Programs By VINOD

month = 1; break;

case 2: case 3: case 11:

month = 4; break;

case 7: case 4:

month = 0; break;

case 5: month = 2; break;

case 6: month = 5; break;

case 8: month = 3; break;

case 9: case 12:

month = 6; break;

} year = year+month; year = year+d; day = year%7; switch(day) { case 0:

printf("Day is SATURDAY"); break;

case 1: printf("Day is SUNDAY"); break;

case 2: printf("Day is MONDAY"); break;

case 3: printf("Day is TUESDAY"); break;

case 4: printf("Day is WEDNESDAY"); break;

6

Page 7: C Programs

C Programs By VINOD

case 5: printf("Day is THURSDAY"); break;

case 6: printf("Day is FRIDAY"); break;

}} getch(); return 0;}

Program for Decimal to Roman Number conversion

#include<stdio.h>

main(){int a,b,c,d,e;clrscr();printf("Input a number (between 1-3000):");scanf("%d",&e);while (e==0||e>3000) { printf ("ERROR: Invalid Input!"); printf ("Enter the number again:"); scanf ("%d",&e); }if (e>3000)

printf("Invalid");a = (e/1000)*1000;b = ((e/100)%10)*100;c = ((e/10)%10)*10;d = ((e/1)%10)*1;

if (a ==1000) printf("M");

else if (a ==2000) printf("MM");

else if (a ==3000) printf("MMM");

if (b == 100) printf("C");

else if (b == 200)

7

Page 8: C Programs

C Programs By VINOD

printf("CC");else if (b == 300)

printf("CCC");else if (b == 400)

printf("CD");else if (b ==500)

printf("D");else if (b == 600)

printf("DC");else if (b == 700)

printf("DCC");else if (b ==800)

printf("DCCC");else if (b == 900)

printf("CM");

if (c == 10) printf("X");

else if (c == 20) printf("XX");

else if (c == 30) printf("XXX");

else if (c == 40) printf("XL");

else if (c ==50) printf("L");

else if (c == 60) printf("LX");

else if (c == 70) printf("LXX");

else if (c ==80) printf("LXXX");

else if (c == 90) printf("XC");

if (d == 1) printf("I");

else if (d == 2) printf("II");

else if (d == 3) printf("III");

else if (d == 4) printf("IV");

else if (d ==5)

8

Page 9: C Programs

C Programs By VINOD

printf("V");else if (d == 6)

printf("VI");else if (d == 7)

printf("VII");else if (d ==8)

printf("VIII");else if (d == 9)

printf("IX");getch();}

Factorial series-e^x

#include <stdio.h>#include <conio.h>#include<math.h>long int factorial(int n);void main(){ int x,i; float s,r; char c; clrscr();printf("You have this series:-1+x/1! + x^2/2! + x^3/3! + x^4/4!..x^x/x!"); printf("To which term you want its sum? "); scanf("%d",&x); s=0; for (i=1;i<=x;i++) {

s=s+((float)pow(x,i)/(float)factorial(i)); } printf("The sum of %d terms is %f",x,1+s); fflush(stdin); getch();}

long int factorial(int n) { if (n<=1)

return(1); else

n=n*factorial(n-1);return(n);

}

9

Page 10: C Programs

C Programs By VINOD

Square Root of a number by using simple calculations

#include<stdio.h>#include<conio.h>main(){ float a,b,e=0.00001,p,k;

clrscr(); do { printf(" PROGRAM TO FIND SQUARE ROOT OF A NUMBER"); printf("ENTER A NUMBER(-1 to Quit) :"); scanf("%f",&k);

a=k;p=a*a;

while(p-k>=e) { b=(a+(k/a))/2; a=b; p=a*a; } printf("SQUARE ROOT IS = %f",a); getch(); clrscr(); }while(k!=-1); getch(); }

Volumes & Areas

/PROGRAM TO CALCULATE AREA,VOLUME,PERIMETER OF A PARTICULAR GEOMETRIC SHAPE/

#include<stdio.h>#include<conio.h>#include<math.h>#define PI 3.14159char ch;main() {

clrscr();

10

Page 11: C Programs

C Programs By VINOD

intro(); getch(); clrscr(); do { ch=menu();

switch(ch) { case 'a': case 'A':

clrscr(); square(); getch(); break;

case 'b': case 'B':

clrscr(); rect(); getch(); break;

case 'c': case 'C':

clrscr(); circl(); getch(); break;

case 'd': case 'D':

clrscr(); tri(); getch(); break;

case 'e': case 'E':

clrscr(); rom(); getch(); break;

case 'f': case 'F':

clrscr(); para();

11

Page 12: C Programs

C Programs By VINOD

getch(); break;

case 'g': case 'G':

clrscr(); tra(); getch(); break;

case 'h': case 'H':

clrscr(); qua(); getch(); break;

case 'i': case 'I':

clrscr(); semicir(); getch(); break;

case 'j': case 'J':

clrscr(); msector(); getch(); break;

case 'k': case 'K':

clrscr(); sphere(); getch(); break;

case 'l': case 'L':

clrscr(); cone(); getch(); break;

case 'm': case 'M':

clrscr(); cyll(); getch();

12

Page 13: C Programs

C Programs By VINOD

break;

case 'n': case 'N':

clrscr(); cube(); getch(); break;

case 'o': case 'O':

clrscr(); cuboid(); getch(); break;

case 'p': case 'P':

clrscr(); hemisphe(); getch(); break;

case 'q': case 'Q':

exit(1); }

} while(ch!='Q'||ch!='q'); getch(); } intro() { int i; clrscr(); printf(""); textcolor(2);

cprintf("################################################################################"); textcolor(4); printf("PROGRAM TO CALCULATE AREAS , VOLUMES ,CIRCUMFERENCES "); printf("====================================================="); printf("OF VARIOUS GEOMETRIC SHAPES"); printf("==========================="); textcolor(2);

13

Page 14: C Programs

C Programs By VINOD

cprintf("################################################################################"); getch();

} menu() { clrscr(); textcolor(7); printf(" MENU

Two Dimensional Shapes.

-----------------------

A.SQUARE B.RECTANGLE

C.CIRCLE D.TRIANGLE

E.RHOMBUS F.PARALLELOGRAM

G.TRAPEZIUM H.QUADRILATERAL.

I.SEMICERCLE J.SECTOR

"); printf(" Three Dimensional Shapes.

-------------------------

K.SPHERE L.CONE M.CYLLINDER

N.CUBE O.CUBOID P.HEMISPHERE

Q.QUIT Enter Your Choice :");

scanf("%c",&ch);

14

Page 15: C Programs

C Programs By VINOD

return(ch); }

/***** SUB FUNCTIONS *****/ /***** 2 D SHAPES *****/

square() { float s,a,p;int i,j; printf(" Enter side of square:"); scanf("%f",&s); a=s*s; p=4*s; printf(" Perimeter of square : %.3f units",p); printf(" Area of square : %.3f sq.units",a); printf("Square is ..."); for(i=1;i<=s;i++)

{ textcolor(10); for(j=1;j<=s;j++) cprintf("ÛÛ"); printf("

"); }

return(0); } rect() { float a,p,l,b; int i,j; printf("Enter length and breadth of rectangle:Length:"); scanf("%f",&l); printf("Breadth:"); scanf("%f",&b); a=l*b; p=2*(l+b); printf(" Perimeter of rectangle : %.3f units",p); printf("Area of rectangle : %.3f sq.units",a); printf("Rectangle is..."); for(i=1;i<=b;i++)

{ textcolor(4); for(j=1;j<=l;j++) cprintf("ÛÛ");

15

Page 16: C Programs

C Programs By VINOD

printf(""); }

return(0); } tri() { float area,p; float a,b,c,s; printf("Enter three sides of triangle:"); scanf( "%f%f%f",&a,&b,&c); p=a+b+c; s=p/2; area=sqrt(s*(s-a)*(s-b)*(s-c)); printf("Perimeter of triangle : %.3f units",p); printf(“Area of a triangle : %.3f sq.units",area); } rom() { float s,d1,d2,a,p; printf("Enter side and diagonals of a rhombus:Side:"); scanf("%f",&s); printf("Diagonal :");scanf("%f",&d1); printf("Diagonal :");scanf("%f",&d2); a=0.5*d1*d2; p=4*s; printf("Perimeter of rhombus :%.3f units",p); printf("Area of rhombus :%.3f sq.units",a); } circl() { float r,a,p; printf("Enter radius of circle:"); scanf("%f",&r); a=PI * r * r; p=2 * PI * r; printf("Circumference of circle : %.3f units",p); printf("Area of circle : %.3f sq.units",a); } para() { float a,p,base,h,l,b; printf("Enter height,length,breadth of parallalogram :" ); printf("Height :"); scanf("%f",&h); printf("Base or Length :"); scanf("%f",&l); printf("Breadth :"); scanf("%f",&b);

16

Page 17: C Programs

C Programs By VINOD

base=l; a=base*h; p=2 * ( l + b ); printf("Perimeter of parallalogram :%.3f units",p); printf("Area of parallogram :%.3f sq.units",a);

}

tra() { float a,b,d,are; printf("Enter height and lengths of two parallel sides:Height :"); scanf("%f",&d); printf("Side:"); scanf("%f",&a); printf("Side:"); scanf("%f",&b); are=0.5 * d * (a+b); printf("Area of trapezium : %.3f sq.units",are); } qua() { float a,b,area,d; printf("Enter diagonal and perpendicular distances from opposite vertices:"); printf("Diagonal :"); scanf("%f",&d); printf("Distance :"); scanf("%f",&a); printf("Distance :");scanf("%f",&b); area= 0.5 * d * (a + b); printf("Area of quadrilateral : %.3f sq.units", area); } semicir() { float a,p,r; printf("Enter radius of semicircle:"); scanf("%f",&r); a=0.5* PI * r * r; p= (PI * r ) + (2 * r); printf(“Circumference of semicircle : %.3f units",p); printf("Area of semicircle : %.3f sq.units",a); }

msector() { float x,r,temp,a,p; printf("Enter radius and angle of sector:"); printf("Radius :");

17

Page 18: C Programs

C Programs By VINOD

scanf("%f",&r); printf("Angle(in degrees) :"); scanf("%f",&x); temp= x/360; a= temp * (PI * r * r); p= temp * (2 * PI * r); printf("Circumference of sector : %.3f units",p); printf("Area of sector : %.3f sq.units",a); }

/******** 3 DIMENSIONAL SHAPES *********/

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

18

Page 19: C Programs

C Programs By VINOD

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

float lsa,tsa,v,r; printf("Enter radius of hemisphere :"); scanf("%f",&r); tsa=3*PI*r*r; lsa=2*PI*r*r; v=(2.0/3.0)*PI*r*r*r; printf("Total surface area of hemisphere :%.3f sq.units",tsa); printf("Lateral surface area of hemisphere :%.3f sq.units",lsa); printf("Volume of hemisphere :%.3f cu.units",v);

19

Page 20: C Programs

C Programs By VINOD

}

/*simple program for “if statement”*/ #include<stdio.h>void main(){

int a;clrscr();if(3+2%5)

printf("This Works\n");

if(a=10)printf("This Works\n");

if(-5)printf("This Works\n");

getch();}

/* program to find a number is positive or negative*/#include<stdio.h>void main(){

int a;clrscr();printf("Enter a Number..\n");scanf("%d", &a);if(a >=0)

printf("%d is positive\n");else

printf("%d is negative\n");getch();

}

/*program to find a number is even or odd*/ #include<stdio.h>void main()

20

Page 21: C Programs

C Programs By VINOD

{int a;

clrscr();

printf("Enter a Number..\n");scanf("%d", &a);

if(a%2 == 0)printf("%d is even\n");

elseprintf("%d is odd\n");

getch();}

/* program to find grade of a student*/#include<stdio.h>void main(){

float avg;

clrscr();

printf("enter your total average..\n");scanf("%f", &avg);

if(avg>=85.0)printf("Distinction\n");

else if(avg>=60.0 && avg<=84.99)printf("First Class\n");

else if(avg>=50.0 && avg<=59.99)printf("Second Class\n");

else if(avg>=35.0 && avg<=40.99)printf("Third Class\n");

21

Page 22: C Programs

C Programs By VINOD

else printf("You Fail\n");

getch();}

/* program to find largest of 3 numbers */#include<stdio.h>void main(){

int a,b,c;

clrscr();

printf("Enter 3 Numbers..\n");scanf("%d%d%d", &a,&b,&c);

printf("The Largest Number Is = ");

if(a > b){

if(a > c)printf("%d\n", a);

elseprintf("%d\n",c);

}else {

if(b > c)printf("%d\n", b);

elseprintf("%d\n",c);

}

getch();}

/*Prg. to correct rudimentary syntax errors*/

#include <stdio.h># include <conio.h>#define NULL 0FILE *fpt;void main(){

22

Page 23: C Programs

C Programs By VINOD

int c1=0,c2=0,c3=0,c4=0,c5=0; char c,name[20],z; clrscr(); printf("Enter the name of file to be checked :- "); gets(name); fpt=fopen(name,"r"); if (fpt==NULL) printf("ERROR - can/'t open file %s",name); else { while ((c=getc(fpt))!=EOF) { if (c=='(') c1=c1+1; if (c==')') c1=c1-1; if (c=='[')

c2=c2+1; if (c==']')

c2=c2-1; if (c=='') {

if (c1!=0) printf("ERROR - Unbalanced parenthesis ()");if (c2!=0) printf("ERROR - Unbalanced brackets []");

} if (c=='{')

c3=c3+1; if (c=='}')

c3=c3-1; if ((int)c==39) {

if (c1!=0){ if (c4==0) c4=c4+1; else c4=c4-1;}else printf("ERROR - Unbalanced ' ");

} if ((int)c==34) {

23

Page 24: C Programs

C Programs By VINOD

if (c1!=0){ if (c5==0) c5=c5+1; else c5=c5-1;}else{ z=(char)34; printf("ERROR - Unbalanced %c ",z);}

} } }

if (c1!=0)printf("ERROR - Unbalanced parenthesis ()");

if (c2!=0)printf("ERROR - Unbalanced brackets []");

if (c3!=0)printf("ERROR - Unbalanced braces {}");

if (c4!=0)printf("ERROR - Unbalanced ' ");

if (c5!=0) printf("ERROR - Unbalanced ' ");

if (c1==0 && c2==0 && c3==0 && c4==0 && c5==0) printf("Program is up to date. WELL DONE!"); fclose(fpt); getch();}

/*Prg. to count no. of characters,no. of blanks,no. of words & no.of lines in a multi line string*/

#include <stdio.h>#include <conio.h>void main(){ char c,choice; int nc=0,nb=0,nw=1,nl=1,count,i/*,flag=1*/; clrscr(); scanf("%c",&choice);

24

Page 25: C Programs

C Programs By VINOD

printf("ENTER STRING:- "); printf("String will be terminated when you press Ctrl-Z."); printf("STRING:- "); while ((c=getchar())!=EOF) { switch(1) {

case 1:

if (c==EOF||c==' '||c=='');

elsenc=nc+1;

case 2: if (c==' ') {

nc=nc+1;nb=nb+1;while((c=getchar())==' '){nb=nb+1;nc=nc+1;}

if (c!=' '){nc=nc+1;nw=nw+1;}

}

case 3: if(c=='') {

nc=nc+1;nb=nb+1;nw=nw+1;nl=nl+1;

} } } printf("no. of characters is %d",nc); printf("no. of blanks is %d",nb);

25

Page 26: C Programs

C Programs By VINOD

printf("no. of words is %d",nw); printf("no. of lines is %d",nl);

fflush(stdin); printf ("Do you want to continue?(y/n):- "); scanf("%c",&choice);

getch();}

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

void sort(void);int c,a[20],l;void main(){ 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; for (i=1;i<=l;i++) { printf("Enter no.:- "); scanf("%d",&a[i]); } for (i=1;i<=(l-1);i++) {

26

Page 27: C Programs

C Programs By VINOD

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) { 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){ int i,j,k,l,b,n;

clrscr(); printf("Enter the value of N:"); scanf("%d",&n);

27

Page 28: C Programs

C Programs By VINOD

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++) printf("%d",j); for(k=n-1;k>=b;k--) printf("%d",k); b--;} getch();}

/*Program for Binary, Octal, Hexadecimal Conversions*/

/*Program for Binary, Octal, Hexadecimal Conversions*/

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

void bd();void db();void doc();void dh();void od();void ob();void bo();void bh();void hb();void hd();void oh();

28

Page 29: C Programs

C Programs By VINOD

void ho();

void main(){

int n; char c; begin: clrscr(); printf(" ****MAIN MENU****"); printf("Enter your choise.(1-12)"); printf("1. Binary to Decimal."); printf("2. Decimal to Binary."); printf("3. Decimal to Octal."); printf("4. Decimal to Hexadecimal."); printf("5. Octal to Decimal."); printf("6. Octal to Binary."); printf("7. Binary to Octal."); printf("8. Binary to Hexadecimal."); printf("9. Hexadecimal to Binary."); printf("10. Hexadecimal to Decimal."); printf("11. Octal to Hexadecimal."); printf("12. Hexadecimal to Octal."); scanf("%d",&n); if(n<1 || n>12) printf("Invalid Choise"); if(n==1) bd(); else if(n==2) db(); else if(n==3) doc(); else if(n==4) { long a; clrscr(); printf("Conversion from Decimal to Hexadecimal"); printf("Enter the decimal number."); scanf("%ld",&a); dh(a); } else if(n==5) od(); else if(n==6) ob(); else if(n==7)

29

Page 30: C Programs

C Programs By VINOD

bo(); else if(n==8) bh(); else if(n==9) hb(); else if(n==10) hd(); else if(n==11) { unsigned long n,i=0,a,p=1,t=0; clrscr(); printf("Conversion from Octal to Hexadecimal."); printf("Enter a Octal number"); scanf("%ld",&n); i=0; while(n!=0) { a=n%10; if(a>7) t=1; n=n/10; i=i+a*p; p=p*8; } if(t==0) { printf("Hexadecimal eq="); oh(i); } else if(t==1) printf("Numbert entered is not octal."); } else if(n==12) ho(); printf("Do you Wish to continue(Y/N)"); scanf("%s",&c); c=toupper(c); if(c=='Y') goto begin; getch();

}

void bd(){

int n,b=0,a[6],i=0,t=0;

30

Page 31: C Programs

C Programs By VINOD

clrscr(); printf("Conversion from Binary to Decimal"); printf("Enter Binary Number"); scanf("%d",&n); while(n!=0) { a[i]=n%10; n=n/10; if(a[i]!=1 && a[i]!=0) t=1; i++; } a[i]=2; n=1; for(i=0;a[i]!=2;i++) { b=b+a[i]*n; n=n*2; } if(t==0) printf("Decimal Equivalent=%d",b); else if(t==1) printf("Entered number is not binary.");

}

void db(){

int dec,bin,n,i=0,a[10]; clrscr(); printf("Conversion from Decimal to Binary"); printf("Input decimal no."); scanf("%d",&dec); do { a[i]=dec%2; dec=dec/2; i++; }while(dec!=0); for(n=i-1;n>=0;n--) printf("%d",a[n]);

}

void doc(){

31

Page 32: C Programs

C Programs By VINOD

int n,i,a[10]; clrscr(); printf("Conversion from Decimal to Octal"); printf("Enter a Decimal number"); scanf("%d",&n); i=0; printf("Octal equavalent of %d is ",n); while(n!=0) { a[i]=n%8; n=n/8; i++; } i--; for(;i>=0;i--) printf("%d",a[i]);

}

void dh(long n){

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

32

Page 33: C Programs

C Programs By VINOD

case 15: printf("F"); break; } } else printf("%ld",i); }

}

void od(){

unsigned long n,i=0,a,p=1,t=0; clrscr(); printf("Conversion from Octal to Decimal"); printf("Enter a Octal number"); scanf("%ld",&n); i=0; printf("Decimal equavalent of %ld",n); while(n!=0) { a=n%10; if(a>7) t=1; n=n/10; i=i+a*p; p=p*8; } if(t==0) printf("= %ld",i); else if(t==1) printf(" can't be calculated because it is not an Octal Number.");

}

void ob(){

int n,a[6],i=0,t=0; clrscr(); printf("Convertion from Octal to Binary."); printf("Enter an Octal Number."); scanf("%d",&n); while(n!=0) { a[i]=n%10; n=n/10;

33

Page 34: C Programs

C Programs By VINOD

if(a[i]>7) t=1; i++; } i--; if(t==0) for(;i>=0;i--) { switch(a[i]) { case 0: printf("000"); break; case 1: printf("001"); break; case 2: printf("010"); break; case 3: printf("011"); break; case 4: printf("100"); break; case 5: printf("101"); break; case 6: printf("110"); break; case 7: printf("111"); break; } } if(t==1) printf("Not a Octal number");

}

void bo(){

int i=0,a[5],t=0; long int n; clrscr();

34

Page 35: C Programs

C Programs By VINOD

printf("Convertion From Binary to Octal"); printf("Enter a Binary number"); scanf("%ld",&n); while(n!=0) { a[i]=n%1000; n=n/1000; if(a[i]>111) t=1; i++; } i--; if(t==0) for(;i>=0;i--) { switch(a[i]) { case 0: printf("0"); break; case 1: printf("1"); break; case 10: printf("2"); break; case 11: printf("3"); break; case 100: printf("4"); break; case 101: printf("5"); break; case 110: printf("6"); break; case 111: printf("7"); break; default: printf("Entered number is not binary.Printed value is notcorrect."); break; }

35

Page 36: C Programs

C Programs By VINOD

} if(t==1) printf("Number is not Binary");

}

void bh(){

int i=0,a[5],t=0; long int n; clrscr(); printf("Convertion from Binary to Hexadecimal"); printf("Enter a Binary number"); scanf("%ld",&n); while(n!=0) { a[i]=n%10000; n=n/10000; if(a[i]>1111) t=1; i++; } i--; if(t==0) for(;i>=0;i--) { switch(a[i]) { case 0: printf("0"); break; case 1: printf("1"); break; case 10: printf("2"); break; case 11: printf("3"); break; case 100: printf("4"); break; case 101: printf("5"); break;

36

Page 37: C Programs

C Programs By VINOD

case 110: printf("6"); break; case 111: printf("7"); break; case 1000: printf("8"); break; case 1001: printf("9"); break; case 1010: printf("A"); break; case 1011: printf("B"); break; case 1100: printf("C"); break; case 1101: printf("D"); break; case 1110: printf("E"); break; case 1111: printf("F"); break; default: printf("Entered number is not binary.Printed value is notcorrect."); break; } } if(t==1) printf("Number is not Binary");

}

void hb(){

int i; char s[20]; clrscr(); printf("Convertion from Hexadecimal to Binary");

37

Page 38: C Programs

C Programs By VINOD

printf("Enter a Hexadecimal number"); scanf("%s",s); /*gets(s);*/ printf("Binary Equivalent="); for(i=0;s[i]!=NULL;i++) { switch(s[i]) { case '0': printf("0000"); break; case '1': printf("0001"); break; case '2': printf("0010"); break; case '3': printf("0011"); break; case '4': printf("0100"); break; case '5': printf("0101"); break; case '6': printf("0110"); break; case '7': printf("0111"); break; case '8': printf("1000"); break; case '9': printf("1001"); break; case 'a': case 'A': printf("1010"); break; case 'b': case 'B':

38

Page 39: C Programs

C Programs By VINOD

printf("1011"); break; case 'c': case 'C': printf("1100"); break; case 'd': case 'D': printf("1101"); break; case 'e': case 'E': printf("1110"); break; case 'f': case 'F': printf("1111"); break; default: printf("Entered number is not Hexadecimal.Printed value is notcorrect."); break; } }

}

void hd(){

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

39

Page 40: C Programs

C Programs By VINOD

case '2': a[i]=2; break; case '3': a[i]=3; break; case '4': a[i]=4; break; case '5': a[i]=5; break; case '6': a[i]=6; break; case '7': a[i]=7; break; case '8': a[i]=8; break; case '9': a[i]=9; break; case 'a': case 'A': a[i]=10; break; case 'b': case 'B': a[i]=11; break; case 'c': case 'C': a[i]=12; break; case 'd': case 'D': a[i]=13; break; case 'e': case 'E': a[i]=14; break; case 'f':

40

Page 41: C Programs

C Programs By VINOD

case 'F': a[i]=15; break; default: printf("Entered number is not Hexadecimal.Printed value is notcorrect."); break; } } i--; for(;i>=0;i--) { h=h+a[i]*m; m=m*16; } printf("%ld ",h);

}

void oh(long n){

long i; if(n>0) { i=n%16; n=n/16; oh(n); if(i>=10) { switch(i) { case 10: printf("A"); break; case 11: printf("B"); break; case 12: printf("C"); break; case 13: printf("D"); break; case 14: printf("E"); break; case 15:

41

Page 42: C Programs

C Programs By VINOD

printf("F"); break; } } else printf("%ld",i); }

}

void ho(){

int i,a[20]; unsigned long int h=0,m=1; char s[20]; clrscr(); printf("Convertion from Hexadecimal to Octal"); printf("Enter a Hexadecimal number"); scanf("%s",s); /* Converting hex to dec first*/ for(i=0;s[i]!=NULL;i++) { switch(s[i]) { case '0': a[i]=0; break; case '1': a[i]=1; break; case '2': a[i]=2; break; case '3': a[i]=3; break; case '4': a[i]=4; break; case '5': a[i]=5; break; case '6': a[i]=6; break; case '7':

42

Page 43: C Programs

C Programs By VINOD

a[i]=7; break; case '8': a[i]=8; break; case '9': a[i]=9; break; case 'a': case 'A': a[i]=10; break; case 'b': case 'B': a[i]=11; break; case 'c': case 'C': a[i]=12; break; case 'd': case 'D': a[i]=13; break; case 'e': case 'E': a[i]=14; break; case 'f': case 'F': a[i]=15; break; default: printf("Entered number is not Hexadecimal.Printed value is notcorrect."); break; } } i--; for(;i>=0;i--) { h=h+a[i]*m; m=m*16; } /* Now convering from decimal to octal (h)*/ i=0;

43

Page 44: C Programs

C Programs By VINOD

printf("Octal equavalent="); while(h!=0) { a[i]=h%8; h=h/8; i++; } i--; for(;i>=0;i--) printf("%d",a[i]);

}

/*Program for computing Area, Volume and Perimeter of Rrectangle usingfunction with looping*/

#include <stdio.h>

void inputoutput () { int comp,ans; clrscr (); printf ("choose please: 1=perimeter,2=area,3=volume] ?: "); scanf ("%d",&comp); if (comp==1) { int le, wi; printf ("Enter the length: "); scanf ("%d",&le); printf ("Enter the width: "); scanf ("%d",&wi); printf ("P=%d",perimeter(le,wi)); } else if (comp==2) { int le, wi; printf ("Enter the length: "); scanf ("%d",&le); printf ("Enter the width: "); scanf ("%d",&wi); printf ("A=%d", area(le,wi)); } else if (comp==3) { int length,width,height; printf ("Enter lenght: ");

44

Page 45: C Programs

C Programs By VINOD

scanf ("%d",&length); printf ("Enter width: "); scanf ("%d",&width); printf ("Enter height: "); scanf ("%d",&height); printf ("V=%d",volume (length,width,height)); }

else inputoutput ();printf ("Do you want to continue? [Yes=1/No=0]: ");scanf ("%d",&ans);if (ans==1)inputoutput ();else printf ("GOOD BYE");

}int perimeter (int l, int w){

int per; per=(l*2)+(w*2); return (per);

}int area (int le, int wi){int are;are=le*wi;return (are);}int volume (int length, int width, int height){int vol;

vol=(length*width*height);return (vol);}

main (){clrscr ();inputoutput ();getch ();}

45

Page 46: C Programs

C Programs By VINOD

/*Program for finding the prime numbers*/

#include <stdio.h>#include <conio.h>void main(){ int n,m,k,i,max; char c; clrscr(); repeat: max=0; k=2; n=1; printf("You want prime numbers upto:- "); scanf("%d",&max); printf(""); for (i=1;i<=max;i++)

{ again: m=(n/k)*k; if (m!=n)k=k+1; elsegoto try1; if (k < n/2)goto again; elseprintf("%d",n);printf(" ");

try1: n=n+1;k=2; }fflush(stdin);

printf ("Do you want to continue?(y/n):- "); scanf("%c",&c); if (c=='y') goto repeat;getch();

}

/*Program for finding the sum of digits of a five digit number*/

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

46

Page 47: C Programs

C Programs By VINOD

{ int n,o,p,q,r,s; char c; clrscr(); repeat: s=0; printf("Enter a five digit no.:- "); scanf("%d",&n); o=n%10000; p=o%1000; q=p%100; r=q%10; s=(n/10000)+(o/1000)+(p/100)+(q/10)+r; printf("The sum of its digits is %d.",s); fflush(stdin);printf ("Do you want to continue?(y/n):- "); scanf("%c",&c); if (c=='y') goto repeat; getch();}

/*Program for Prime Number Generation*/

#include <stdio.h>main(){

int n,i=1,j,c; clrscr(); printf("Enter Number Of Terms"); printf("Prime Numbers Are Follwing"); scanf("%d",&n); while(i<=n) { c=0; for(j=1;j<=i;j++) {

if(i%j==0) c++;

} if(c==2) printf("%d ",i); i++; } getch();

47

Page 48: C Programs

C Programs By VINOD

}

/*Program Implementing the rot13 algorithm*/

#include<stdio.h>#define ROT 13

int main(void){

int c,e;

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

if(c >='A' && c <='Z'){

if((e = c + ROT) <= 'Z')putchar(e);

else{

e = c - ROT;putchar(e);

}}else if(c >='a' && c <='z'){

if((e= c + ROT) <= 'z')putchar(e);

else{

e = c - ROT;putchar(e);

}}else

putchar(c);}

return 0;}

/*Program of Falling Characters*/

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

48

Page 49: C Programs

C Programs By VINOD

#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++) { 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."); printf("STRING:- "); while ((c=getchar())!=EOF) { if (c=='a'||c=='A') a=a+1; if (c=='e'||c=='E') e=e+1;

49

Page 50: C Programs

C Programs By VINOD

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();}

/*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) { a[i][j]=a[i-1][c-1]+a[i-1][c-2]; printf("%5d",a[i][j]); c=c+1; j=j+1; }

50

Page 51: C Programs

C Programs By VINOD

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

getch();}

/*Program to calculate the sum of series*/

#include <stdio.h>#include <conio.h>long int factorial(int n);void main(){ int n,i; float s,r; char c; clrscr(); repeat : printf("You have this series:- 1/1! + 2/2! + 3/3! + 4/4! ..."); printf("To which term you want its sum? "); scanf("%d",&n); s=0; for (i=1;i<=n;i++) { s=s+((float)i/(float)factorial(i)); } printf("The sum of %d terms is %f",n,s); fflush(stdin); printf ("Do you want to continue?(y/n):- "); scanf("%c",&c); if (c=='y') goto repeat; getch();}

long int factorial(int n) { if (n<=1)

return(1); else

n=n*factorial(n-1);return(n);

}

/*Factorial Function*/

51

Page 52: C Programs

C Programs By VINOD

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

s=s+((float)i/(float)factorial(i)); } printf("The sum of %d terms is %f",n,s); fflush(stdin); printf ("Do you want to continue?(y/n):- "); scanf("%c",&c); if (c=='y') goto repeat; getch();}

long int factorial(int n) { if (n<=1)

return(1); else

n=n*factorial(n-1);return(n);

}

/* Prg. to convert upper case to lower case or lower case to upper casedepending on the name it is invoked with as found in argument.*/

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

void lower_to_upper();void upper_to_lower();void main()

52

Page 53: C Programs

C Programs By VINOD

{ int n; clrscr(); printf("Please enter your choice."); printf("(1) for upper to lower conversion."); printf("(2) for lower to upper conversion."); printf("CHOICE:- "); scanf("%d",&n); switch (n) { case 1:

{printf("Please enter a string in upper case.");printf("String will be terminated if you press Ctrl-Z.");printf("STRING:- ");upper_to_lower();break; }

case 2: {printf("Please enter a string in lower case.");printf("String will be terminated if you press Ctrl-Z.");printf("STRING:- ");lower_to_upper();break; }

default:printf("ERROR");

} printf("HAVE A NICE DAY! BYE."); getch();} void upper_to_lower() { int i,j; char c4[80],c3; for (i=0;(c3=getchar())!=EOF;i++)

c4[i]=(c3>='A' && c3<='Z')?('a' + c3 -'A'):c3; printf("The lower case equivalent is "); for (j=0;j<i;j++)

putchar(c4[j]); return; }

53

Page 54: C Programs

C Programs By VINOD

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;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;

}dd2=func1(mon2)+dd2+day2+((year2-ref)*365);printf("No. of days from the reference year's first Jan = %d",dd2);

54

Page 55: C Programs

C Programs By VINOD

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;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);

printf("CHOICE:-"); printf("(1) Sort in ascending order."); printf("(2) Sort in descending order.");

55

Page 56: C Programs

C Programs By VINOD

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; 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) { 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;

56

Page 57: C Programs

C Programs By VINOD

}

/*Merge sort*/

#include<stdio.h>

void getdata(int arr[],int n){ int i; printf("enter the data:"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); }}

void display(int arr[],int n){ int i; printf(""); for(i=0;i<n;i++) { printf("%d ",arr[i]); } getchar();}

void sort(int arr[],int low,int mid,int high){ int i,j,k,l,b[20]; l=low; i=low; j=mid+1; while((l<=mid)&&(j<=high)) { if(arr[l]<=arr[j]) { b[i]=arr[l]; l++; } else { b[i]=arr[j]; j++; } i++; } if(l>mid) { for(k=j;k<=high;k++) { b[i]=arr[k];

57

Page 58: C Programs

C Programs By VINOD

i++; } } else { for(k=l;k<=mid;k++) { b[i]=arr[k]; i++; } } for(k=low;k<=high;k++) { arr[k]=b[k]; }}

void partition(int arr[],int low,int high){ int mid; if(low<high) { mid=(low+high)/2; partition(arr,low,mid); partition(arr,mid+1,high); sort(arr,low,mid,high); }}

void main(){ int arr[20]; int n; printf("Enter number of data:"); scanf("%d",&n); getdata(arr,n); partition(arr,0,n-1); display(arr,n); getchar();}

/*No guessing*/

#include<conio.h>#include<stdlib.h>#include<stdio.h>#include<process.h>int no=0;int client[4];

58

Page 59: C Programs

C Programs By VINOD

void calno(int);void main(){

int x[4],check,k,tiger,goat,score=1000; char ch;int i,count,m,n,j;clrscr();

/*Random no generation*********************** */ randomize(); while(1){ x[0]=random(9); if(x[0]!=0) break; } while(1){ x[1]=random(9); if(x[0]!=x[1]) break; } while(1){ x[2]=random(9); if(x[2]!=x[1]&&x[2]!=x[0]) break; } while(1){ x[3]=random(9); if(x[3]!=x[2]&&x[3]!=x[1]&&x[3]!=x[0]) break; } /* ******************************************** */

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

/* starting of guessing****************** */

for(i=1;i<=10;i++){ tiger=0;

59

Page 60: C Programs

C Programs By VINOD

goat=0; printf("Enter the %d guess: ",i); scanf("%d",&check); calno(check); for(count=0;count<4;count++){ if(x[count]==client[count]) tiger=tiger+1; } printf("You have got %d tiger",tiger); if(tiger==4) break;

/*---------------check for goat----------------------*/ for(m=0;m<4;m++){ for(n=0;n<4;n++){ if(client[m]!=x[m]){ if(client[m]==x[n]) goat=goat+1; } } }

printf(" and %d goat",goat); score=score-100;

} if(tiger<4){ printf("-----Sorry u have lost the game-----"); printf("the no is "); for(j=0;j<4;j++){ printf("%d",x[j]); } }

else printf("-----You have got the no in %d guess and you score is%d----",j,score);

getch(); }

void calno(int no){ int a=no,x,y; client[3]=a%10; x=a/10; client[2]=x%10; y=a/100; client[1]=y%10; client[0]=a/1000; }

Invoke function without main in C Language

#include<stdio.h>

60

Page 61: C Programs

C Programs By VINOD

#include<conio.h>

#define FIRST 0#define SECOND 1#define THIRD 2

//Variablesint a,b,c,ch;float d;//Function Prototypevoid Read();void Operation();void Display();

#pragma startup Read 0 //First_Priority#pragma startup Operation 1 //Second_Priority#pragma exit Display //Third_Priority

void main(){ printf("

Enter to main() "); getch(); printf("

Exit From main() "); getch();}

void Read(){ clrscr(); printf("Enter the value of a : "); scanf("%d",&a); printf("Enter the value of b : "); scanf("%d",&b);}

void Operation(){ printf("ArithMetic Operations"); printf("---------------------"); printf("1 -> Addition "); printf("2 -> Subtraction"); printf("3 -> Multiplication

61

Page 62: C Programs

C Programs By VINOD

"); printf("---------------------"); scanf("%d",&ch); switch(ch) { case 1: c = a+b; break; case 2: c = a-b; break; case 3: c = a*b; break; }}

void Display(){ switch(ch) { case 1: printf("

The Result (Addition) : %d",c); break; case 2: printf("

The Result (Subtraction): %d",c); break; case 3: printf("

The Result (Multiplication): %d",c); break; } getch();}

Calendar of Thousands of Years

#include<stdio.h>#include<conio.h>static char *months[]={"January",

"February", "March", "April", "May",

62

Page 63: C Programs

C Programs By VINOD

"June", "July", "August", "September", "October", "November", "December"};

void main(){static int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};long int ndays,ldays,tydays,tdays;int d,i,m,fday,y;char ch;textcolor(LIGHTGREEN);textbackground(LIGHTBLUE);clrscr();printf("Enter year(1900 onwards) & month(number):");scanf("%d%d",&y,&m);while(1){ndays=(y-1)*365l;ldays=(y-1)/4-(y-1)/100+(y-1)/400;tdays=ndays+ldays;//total days//check for leap yearif((y%100==0 && y%400==0)||(y%4==0 && y%100!=0))days[1]=29;elsedays[1]=28;d=days[m-1];tydays=0;for(i=0;i<=m-2;i++)tydays=tydays+days[i];tdays=tydays+tdays;fday=tdays%7;cal(y,m,fday,d);ch=getche();switch(ch){case 77:if(m==12){y++;m=1;}elsem++;break;case 72:y++;continue;case 75:if(m==1){y--;

63

Page 64: C Programs

C Programs By VINOD

m=12;}elsem--;break;case 80:y--;continue;case 27:exit(0);}}}cal(int yr,int mo,int fd,int da){int i,r,c;char a;clrscr();gotoxy(25,2);printf("%s %d",months[mo-1],yr);textcolor(LIGHTGREEN);gotoxy(5,5);printf("____________________________________________________");gotoxy(10,6);printf("MON TUE WED THU FRI SAT SUN");gotoxy(5,7);printf("____________________________________________________");r=9;c=11+(6*fd);for(i=1;i<=da;i++){gotoxy(c,r);if(c==47)textcolor(RED);elsetextcolor(LIGHTGREEN);cprintf("%d",i);if(c<=41)c=c+6;else{c=11;r=r+1;}}textcolor(LIGHTGREEN);gotoxy(5,15);printf("____________________________________________________");gotoxy(11,17);printf("UP-Next Year DOWN-Prev Year");gotoxy(11,18);printf("RIGHT-Next Month LEFT-Prev Month");gotoxy(27,20);printf("Esc-Exit");return 0;}

64

Page 65: C Programs

C Programs By VINOD

/*Calender Program in C*/

/*Program to display calender for a given year*/

#include <stdio.h>#include <conio.h>#include <process.h>#include <ctype.h>

unsigned long days=0;/*stores the days elapsed since 01.01.1899*/void display(int n)/*contains the number of days to display*/{

int i, column, k, flag=0, j;printf("Sun Mon Tues Wed Thur Fri Sat");for(i=1; i<=n; i++){k=days%7;/*remainder gives the starting day of each month*/if(flag==0){for(j=1; j<=k; j++)/*controls tabs of first week*/printf(" ");flag=1;/*ensures that block is only executed once*/column=k;}printf("%d ", i);column++;if(column%7==0)/*prints new line at the end of each week*/printf("");}printf("Press any key to continue");getch();

}

void calculate(int year)/*function calculates no. of days elapsed since 1899*/{

int i, month;for(i=1899; i<year; i++)

/*1899 chosen because Jan 1, 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 everyfourth year. If a year is divisible by 4, then it is a leapyear, but if that year is divisible by 100, then it isnot a leap year. However, if the year is also divisible by400, then it is a leap year. Eg: 1900 is not a leap year*/

days+=366;else

65

Page 66: C Programs

C Programs By VINOD

days+=365;}for(month=1; month<=12; month++){printf("");switch(month)

/*switch case used to display each month andincrement no. of days*/{case 1: printf(" JANUARAY %d", year);display(31);days+=31;break;case 2: printf(" FEBURARY %d", year);if((year%400==0)?1:((year%100==0)?0:((year%4==0)?1:0))){display(29);days+=29;}else{display(28);days+=28;}break;case 3: printf(" MARCH %d", year);display(31);days+=31;break;case 4: printf(" APRIL %d", year);display(30);days+=30;break;case 5: printf(" MAY %d", year);display(31);days+=31;break;case 6: printf(" JUNE %d", year);display(30);days+=30;break;case 7: printf(" JULY %d", year);display(31);days+=31;break;case 8: printf(" AUGUST %d", year);display(31);days+=31;break;case 9: printf(" SEPTEMBER %d", year);display(30);days+=30;break;case 10: printf(" OCTOBER %d", year);

66

Page 67: C Programs

C Programs By VINOD

display(31);days+=31;break;case 11: printf(" NOVEMBER %d", year);display(30);days+=30;break;case 12: printf(" DECEMBER %d", year);display(31);days+=31;break;}}

}

void main(){

char ch[10];int i, year, choice;do{clrscr();days=0;printf("Enter the year in 'yyyy' format:");scanf("%s", ch);/*stores input first as a string*/for(i=0; i<strlen(ch); i++)if(ch[i]<'0' || ch[i]>'9')/*checks for invalid inputs*/{printf("Invalid Year!");printf("END OF PROGRAM");getch();exit(0);}year = atoi(ch);

/*converts the year from string to integer datatype*/clrscr();printf("Calender for Year %d", year);printf("**********************");calculate(year);

/*calls function to calculate no. of days elapsed*/

printf("*******************************************");printf("Press 1 to continue, 2 to exit");scanf("%d", &choice);}while(choice==1);clrscr();printf("END OF PROGRAM");getch();

}

INTERVIEW QUESTIONS C

Predict the output or error(s) for the following:

67

Page 68: C Programs

C Programs By VINOD

1. void main(){

int const * p=5;printf("%d",++(*p));

}Answer:

Compiler error: Cannot modify a constant value.Explanation:p is a pointer to a "constant integer". But we tried to change the valueof the "constant integer".

2. main(){

char s[ ]="man";int i;for(i=0;s[ i ];i++)printf("

%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}Answer: mmmm aaaa nnnnExplanation:s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the sameidea. Generally array name is the base address for that array. Here s isthe base address. i is the index number/displacement from the baseaddress. So, indirecting it with * is same as s[i]. i[s] may besurprising. But in the case of C it is same as s[i].

3. main(){

float me = 1.1;double you = 1.1;if(me==you)

printf("I love U");else

printf("I hate U");}Answer:I hate UExplanation:For floating point numbers (float, double, long double) the values cannotbe predicted exactly. Depending on the number of bytes, the precessionwith of the value represented varies. Float takes 4 bytes and long doubletakes 10 bytes. So float stores 0.9 with less precision than long double.Rule of Thumb:

68

Page 69: C Programs

C Programs By VINOD

Never compare or at-least be cautious when using floating point numberswith relational operators (== , >, <, <=, >=,!= ) .

4. main(){static int var = 5;printf("%d ",var--);if(var)

main();}

Answer:5 4 3 2 1 Explanation:When static storage class is given, it is initialized once. The change inthe value of a static variable is retained even between the functioncalls. Main is also treated like any other ordinary function, which can becalled recursively.

5. main(){

int c[ ]={2.8,3.4,4,6.7,5}; int j,*p=c,*q=c; for(j=0;j<5;j++) {

printf(" %d ",*c); ++q; } for(j=0;j<5;j++){

printf(" %d ",*p);++p; }}

Answer: 2 2 2 2 2 2 3 4 6 5 Explanation:Initially pointer c is assigned to both p and q. In the first loop, sinceonly q is incremented and not c , the value 2 will be printed 5 times. Insecond loop p itself is incremented. So the values 2 3 4 6 5 will beprinted.

6. main(){

extern int i;i=20;

printf("%d",i);}

Answer:Linker Error : Undefined symbol '_i'Explanation: extern storage class in the following declaration, extern int i;

69

Page 70: C Programs

C Programs By VINOD

specifies to the compiler that the memory for i is allocated in some otherprogram and that address will be given to the current program at the timeof linking. But linker finds that no other variable of name i is availablein any other program with memory space allocated for it. Hence a linkererror has occurred .

7. main(){

int i=-1,j=-1,k=0,l=2,m;m=i++&&j++&&k++||l++;printf("%d %d %d %d %d",i,j,k,l,m);

}Answer: 0 0 1 3 1Explanation :Logical operations always give a result of 1 or 0 . And also the logicalAND (&&) operator has higher priority over the logical OR (||) operator.So the expression ‘i++ && j++ && k++’ is executed first. The result ofthis expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2which evaluates to 1 (because OR operator always gives 1 except for ‘0 ||0’ combination- for which it gives 0). So the value of m is 1. The valuesof other variables are also incremented by 1.

8. main(){

char *p;printf("%d %d ",sizeof(*p),sizeof(p));

}

Answer: 1 2Explanation:The sizeof() operator gives the number of bytes taken by its operand. P isa character pointer, which needs one byte for storing its value (acharacter). Hence sizeof(*p) gives a value of 1. Since it needs two bytesto store the address of the character pointer sizeof(p) gives 2.

9. main(){

int i=3;switch(i) { default:printf("zero"); case 1: printf("one");

70

Page 71: C Programs

C Programs By VINOD

break; case 2:printf("two");

break; case 3: printf("three");

break; }

}Answer :threeExplanation :The default case can be placed anywhere inside the loop. It is executedonly when all other cases doesn't match.

10. main(){

printf("%x",-1<<4);}Answer:fff0Explanation :-1 is internally represented as all 1's. When left shifted four times theleast significant 4 bits are filled with 0's.The %x format specifierspecifies that the integer value be printed as a hexadecimal value.

11. main(){

char string[]="Hello World";display(string);

}void display(char *string){

printf("%s",string);} Answer:Compiler Error : Type mismatch in redeclaration of function display Explanation :In third line, when the function display is encountered, the compilerdoesn't know anything about the function display. It assumes the argumentsand return types to be integers, (which is the default type). When it seesthe actual function display, the arguments and type contradicts with whatit has assumed previously. Hence a compile time error occurs.

12. main(){

int c=- -2;printf("c=%d",c);

}Answer: c=2; Explanation:

71

Page 72: C Programs

C Programs By VINOD

Here unary minus (or negation) operator is used twice. Same maths rulesapplies, ie. minus * minus= plus.Note:However you cannot give like --2. Because -- operator can only be appliedto variables as a decrement operator (eg., i--). 2 is a constant and not avariable.

13. #define int charmain(){

int i=65;printf("sizeof(i)=%d",sizeof(i));

}Answer: sizeof(i)=1Explanation:Since the #define replaces the string int by the macro char

14. main(){int i=10;i=!i>14;printf("i=%d",i);}Answer:i=0

Explanation:In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’symbol. ! is a unary logical operator. !i (!10) is 0 (not of true isfalse). 0>14 is false (zero).

15. #include<stdio.h>main(){char s[]={'a','b','c','','c','

C++

Class with constructor ( for bank account )

# include<iostream.h>72

Page 73: C Programs

C Programs By VINOD

# include<conio.h># include<iomanip.h>

class bank{char name[20];int acno;char actype[4];float balance;public:// Constuctorbank(){

cout<<"Constructor Invoked !";acno = 0000;balance = 0.0;

}void init();void deposit();void withdraw();void disp_det();};

//member functions of bank classvoid bank :: init(){cout<<"

New Account";cout<<"

Enter the Name of the depositor : ";cin.get(name,19,'');cout<<"Enter the Account Number : ";cin>>acno;cout<<"Enter the Account Type : (CURR/SAVG/FD/RD/DMAT) ";cin>>actype;cout<<"Enter the Amount to Deposit : ";cin >>balance;}void bank :: deposit()

73

Page 74: C Programs

C Programs By VINOD

{float more;cout <<"

Depositing";cout<<"

Enter the amount to deposit : ";cin>>more;balance+=more;}void bank :: withdraw(){float amt;cout<<"

Withdrwal";cout<<"

Enter the amount to withdraw : ";cin>>amt;balance-=amt;}void bank :: disp_det(){cout<<"

Account Details

";cout<<"Name of the depositor : "<<name<<endl;cout<<"Account Number : "<<acno<<endl;cout<<"Account Type : "<<actype<<endl;cout<<"Balance : $"<<balance<<endl;}// main function , exectution starts herevoid main(void){clrscr();bank obj;int choice =1;while (choice != 0 ){cout<<"

74

Page 75: C Programs

C Programs By VINOD

Enter 0 to exit1. Initialize a new acc.2. Deposit3.Withdraw4.See A/c Status";

cin>>choice;switch(choice){

case 0 :obj.disp_det();cout<<"

EXITING PROGRAM.";break;

case 1 : obj.init();break;

case 2: obj.deposit();break;

case 3 : obj.withdraw();break;

case 4: obj.disp_det();break;

default: cout<<"

Illegal Option"<<endl;}}getch();}

Program to calculate the Typing Speed

#include <stdio.h>#include <dos.h>#include <conio.h>#define ESC 0x1b#define BSPACE 0x08

const unsigned long far * const dosTime = (const unsigned long far * const)MK_FP( 0x40, 0x6C );

class Timer{

75

Page 76: C Programs

C Programs By VINOD

public:

Timer(); void start(); void stop(); void reset(); int status(); double time(); static double resolution();private:

static unsigned adjust; static unsigned calibrate(); int running; struct TIME

{ unsigned long dosCount; unsigned timerCount; };

TIME startTime; double time_;};

inline double Timer::time(){ return time_/1.E6;}

inline double Timer::resolution(){ return 839/1.E9;}

unsigned Timer::adjust = calibrate();

Timer::Timer() : time_(0), running(0){}

void Timer::start(){ if( !running )

{ outportb( 0x43, 0x34 ); asm jmp __1;

76

Page 77: C Programs

C Programs By VINOD

__1: outportb( 0x40, 0 ); asm jmp __2;

__2: outportb( 0x40, 0 ); startTime.dosCount = *dosTime; startTime.timerCount = 0; running = 1; }

}

void Timer::stop(){ outportb( 0x43, 0 ); unsigned char temp = inportb( 0x40 );

TIME stopTime; stopTime.timerCount = (inportb( 0x40 ) << 8) + temp; stopTime.dosCount = *dosTime;

TIME elapsedTime; elapsedTime.dosCount = stopTime.dosCount - startTime.dosCount; elapsedTime.timerCount = -( stopTime.timerCount - adjust );

const double fudge = 83810.0/100000.0; time_ += ((elapsedTime.dosCount << 16) +elapsedTime.timerCount)*fudge;

running = 0;

}

void Timer::reset(){ time_ = 0; if( running )

start();}

unsigned Timer::calibrate(){ adjust = 0; unsigned long sum = 0; Timer w; for( int i = 0; i < 100; i++ )

77

Page 78: C Programs

C Programs By VINOD

{ w.start(); w.stop(); sum += w.time(); w.reset(); }

return (unsigned)((sum+5)/100);}

void main(){ clrscr(); Timer t; char text[1000]; int i = 0, space_count = 0, letter_count = 0; float duration; printf("

PROGRAM TO TEST TYPING SPEED"); printf("Hit any key to start timer...

"); if(getch()) { printf("Your time has started. Start typing. Hit Esc when done.

"); t.start(); } while(1) { text[i] = getche(); letter_count++; if(text[i] == ' ') space_count++; if(text[i] == '') printf(""); if(text[i] == BSPACE) printf(" "); // to erase previous character instead of cursoringover if(text[i] == ESC) {

78

Page 79: C Programs

C Programs By VINOD

printf(" "); // to eliminate a special character that is printed for Esc // A Backspace followed by Space erases previous character. break; } }

t.stop(); duration = t.time(); printf("

Your typing speed is :

"); printf("%6.2f characters per minute",60*letter_count/duration); printf("%6.2f words per minute (Actual)",60*space_count/duration); printf("%6.2f words per minute (Average)",60*letter_count/duration/5);

getch();}

/*Program to convert input decimal value to its hexadecimal equivalent*/

#include <stdio.h>#include <conio.h>#include <math.h>void dtoh(int d);main(){

int d; clrscr(); printf("Enter a no. in decimal system:- "); scanf("%d",&d); dtoh(d); printf("\n\nHAVE A NICE DAY! BYE.");

79

Page 80: C Programs

C Programs By VINOD

getch();}

void dtoh(int d) { int b,c=0,a[5],i=0; b=d; while (b>15) { a[i]=b%16; b=b/16; i++; c++; } a[i]=b; printf("Its hexadecimal equivalent is "); for (i=c;i>=0;--i) { if (a[i]==10)

printf("A"); else if (a[i]==11)

printf("B"); else if (a[i]==12)

printf("C"); else if (a[i]==13)

printf("D"); else if (a[i]==14)

printf("E"); else if (a[i]==15)

printf("F"); else

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

/*Program to Convert Numbers into Words*/

#include<stdio.h>

void pw(long,char[]);char *one[]={" "," one"," two"," three"," four"," five"," six"," seven","eight"," Nine"," ten"," eleven","

twelve"," thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen"};

80

Page 81: C Programs

C Programs By VINOD

char *ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};

void main(){ long n; clrscr(); printf("Enter any 9 digit no: "); scanf("%9ld",&n); if(n<=0) printf("Enter numbers greater than 0"); else { pw((n/10000000),"crore"); pw(((n/100000)%100),"lakh"); pw(((n/1000)%100),"thousand"); pw(((n/100)%10),"hundred"); pw((n%100)," "); } getch();}

void pw(long n,char ch[]){ (n>19)?printf("%s %s ",ten[n/10],one[n%10]):printf("%s ",one[n]); if(n)printf("%s ",ch);}

/*Program to copy its input to its output replacing string of oneor more blanks by a single blank*/

#include <stdio.h>#include <conio.h>void main(){ char c; clrscr(); printf("Enter a line of text:- "); printf("String will be terminated if you press ENTER."); printf("Press Ctrl-Z & then ENTER to end the task."); printf("STRING:- "); c=getchar(); printf("Justified form:- ");

81

Page 82: C Programs

C Programs By VINOD

while (c!=EOF) {

if (c==' ')putchar(c);while (c==' '){ c=getchar();}putchar(c);c=getchar();

} getch();}

/*Program to count the number of words in an input text file*/

#include<stdio.h>

#define NULL 0FILE *fpt;void main(){

char name[20],c; int nw=0; clrscr(); printf("Enter the name of file to be checked:- "); gets(name); fpt=fopen(name,"r"); if (fpt==NULL) { printf("ERROR - can/'t open file %s",name); getch(); exit(0); } else { while ((c=getc(fpt))!=EOF) { switch(1) {

82

Page 83: C Programs

C Programs By VINOD

case 1: if (c==' ') {

point: do nw=nw+1-1;

while((c=getc(fpt))==' ');

if (c!=' ')nw=nw+1;

if(c=='')nw--; }

case 3: if(c==''){ goto point;}

} } } printf("The no. of words in %s is %d. ",name,nw); getch();}

WORK OUT/*Program to Delete Duplicates in Array*/

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

int i,j,l,t=1; char y,s[15]; clrscr(); s[0]='E'; s[1]='n'; s[2]='t'; s[3]='e'; s[4]='r'; s[5]=' '; s[6]='a'; s[7]=' ';

83

Page 84: C Programs

C Programs By VINOD

s[8]='s'; s[9]='t'; s[10]='r'; s[11]='i'; s[12]='n'; s[13]='g'; s[14]=NULL; printf("Enter a string"); gotoxy(1,2); while((y=getchar())!='') { for(i=3,l=200;i<=24;i++,l=l+50) { gotoxy(t,i); if(y!=' ') { printf("%c",y); gotoxy(t,i-1); printf(" "); sound(l); delay(80); } } t++; } gotoxy(1,1); t=1; for(j=0,l=100;j<14;j++,l=l+50) { if(l>200) l=100; for(i=2;i<24;i++,l++) { gotoxy(t,i); if(s[j]!=' ') { printf("%c",s[j]); gotoxy(t,i-1); printf(" "); sound(l); delay(80); } } t++; }

84

Page 85: C Programs

C Programs By VINOD

nosound(); getch();

}

/*Program to display Binary equivalent of an input Hexadecimal Number(Hexadecimal to Binary Converter)*/

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

char z[5],c; int i=0; clrscr(); printf("Enter a hexadecimal no."); printf("Number will be accepted if you press Ctrl-Z & then ENTER after inputting no."); printf("NUMBER:- " ); while ((c=getchar())!=EOF) { printf(" "); if (c=='1') printf("0001"); else if (c=='2') printf("0010"); else if (c=='3') printf("0011"); else if (c=='4') printf("0100"); else if (c=='5') printf("0101"); else if (c=='6') printf("0110"); else if (c=='7') printf("0111"); else if (c=='8') printf("1000"); else if (c=='9') printf("1001"); else if (c=='A'||c=='a') printf("1010"); else if (c=='B'||c=='b') printf("1011");

85

Page 86: C Programs

C Programs By VINOD

else if (c=='C'||c=='c') printf("1100"); else if (c=='D'||c=='d') printf("1101"); else if (c=='E'||c=='e') printf("1110"); else if (c=='F'||c=='f') printf("1111"); else { printf("ERROR");

getch();exit(0); }

} printf("is its binary equivalent."); getch();}

/*Program to display decimal equivalent of a input binary number*/

#include <stdio.h>#include <conio.h>#include <math.h>void btod(int b[]);int c;void main(){

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

86

Page 87: C Programs

C Programs By VINOD

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

/*Program to display hexadecimal equivalent of a input binary number.*/

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

87

Page 88: C Programs

C Programs By VINOD

s=btod(a); dtoh(s); printf("HAVE A NICE DAY! BYE."); getch();}

int btod(int b[]) { int k,s=0,i,n; n=*b; for (i=c-1;i>=0;--i) { if (i>0)

*b=*(b+i); else

*b=n; if (*b==1) {

k=pow(2,i);s=s+k;

} } return(s); }

void dtoh(int s) { int b,c=0,a[5],i=0; b=s; while (b>15) { a[i]=b%16; b=b/16; i++; c++; } a[i]=b; printf("Its hexadecimal equivalent is "); for (i=c;i>=0;--i) { if (a[i]==10)

printf("A"); else if (a[i]==11)

88

Page 89: C Programs

C Programs By VINOD

printf("B"); else if (a[i]==12)

printf("C"); else if (a[i]==13)

printf("D"); else if (a[i]==14)

printf("E"); else if (a[i]==15)

printf("F"); else

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

/*Program to find an input substring in an input main string*/#include<stdio.h>

void main(){

int i=0,j=0,k=0,count=0,l=0,k1=0; char a[80],b[80]; clrscr(); printf("Enter main string:-"); gets(a); printf("Enter sub-string:-"); gets(b);

l=strlen(b); while (a[i]!=EOF) { if (a[i]==b[j]) { i++; j++; k1=1; if (j==l) { j=0; k=1; count=count+1; }

89

Page 90: C Programs

C Programs By VINOD

} else { if (k1==1) { j=0; k1=0; } else i++; } }

if (k==1) { printf("The given sub-string is present in the main string."); printf("It is present %d times.",count); } else { if (k==0) printf("The given sub-string is not present in the main string."); } getch();}

/*Program to find day when a date is given*/

#include<stdio.h>main(){int d,m,y,i;int r=0,r1=0,r2=0,s=0;clrscr();

input:printf("Enter the DATE MONTH and YEAR");scanf("%d %d %d",&d,&m,&y); if(m==2){ if((d>28)&&(y%4!=0)){ printf("Fool,Invalid date in February of non leap year.The maximum value is 28"); goto input;

90

Page 91: C Programs

C Programs By VINOD

} if((d>29)&&(y%4==0)){ printf("Fool,Invalid date in February of leap year.The maximum value is 29"); goto input; } } 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",m); goto input; } } else if(((m==4)||(m==6)||(m==9)||(m==11))&&(d>30)){ printf("Fool,Invalid date in the %d th month.The maximum value is 30",m);

goto input; } else if((d>31)){printf("Enter valid date");goto input;}if((d<1)||(m<1)){printf("Fool,Enter positive valid data");goto input;} else {

switch(m){case 1:case 10:r1=d+2;break;case 2:case 3:case 11:r1=d+5;break;case 4:case 7:r1=d+1;break;case 9:case 12:r1=d;break;

91

Page 92: C Programs

C Programs By VINOD

case 5:r1=d+3;break;case 6:r1=d+6;break;case 8:r1=d+4;break;default:{printf("Don't U know that there is no month greater than 12.Enter validmonthOnce again enter the

Date Month Year");goto input;}}}if(y<2003){ for(i=2002;i>=y;i--){ if((i==y)&&(i%4==0)){ if(m>2) s=s+1; else if(m<=2) s=s+2; break; }

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

92

Page 93: C Programs

C Programs By VINOD

} else if(i%4==0){ if(i%100==0){ if(i%400==0) s=s+2; else s=s+1; } else s=s+2; } else s=s+1; } r2=s%7; }else r2=0;r=(r1+r2)%7;printf("");switch(r){case 0:printf("The Day is SUNDAY");break;case 1:printf("The Day is MONDAY");break;case 2:printf("The Day is TUESDAY");break;case 3:printf("The Day is WEDNESDAY");break;case 4:printf("The Day is THURSDAY");break;case 5:printf("The Day is FRIDAY");break;case 6:printf("The Day is SATURDAY");break;}printf("Thanks for using my program");getch();}

93

Page 94: C Programs

C Programs By VINOD

/*Program to find Determinant of a Matrix*/

#include<stdio.h>#include<conio.h>#define LIMIT 10void main(){ int chckdgnl(); float deter(); float a[LIMIT][LIMIT],value; int i,j,order; clrscr(); printf("Enter order of determent :"); scanf("%d",&order); for(i=0;i<order;i++) {

for(j=0;j<order;j++){ printf("Enter (%d,%d) element of the determent :",i+1,j+1); scanf("%f",&a[i][j]);}

}

if(chckdgnl(a,order)==0) value=0;

else value=deter(a,order);

printf("Determinent Value :%f",value); getch();}

float deter(float a[][LIMIT],int forder){ int i,j,k; float mult; float deter=1; for(i=0;i<forder;i++) {

for(j=0;j<forder;j++){ mult=a[j][i]/a[i][i]; for(k=0;k<forder;k++) {

if(i==j) break;a[j][k]=a[j][k]-a[i][k]*mult;

94

Page 95: C Programs

C Programs By VINOD

}}

} for(i=0;i<forder;i++) {

deter=deter*a[i][i]; } return(deter);}

int chckdgnl(float array[][LIMIT],int forder){ int i,j,k; float nonzero; for(i=0;i<forder;i++) {

if(array[i][i]==0) {

for(j=0;j<forder;j++){ if(array[i][j]!=0) {

k=j; break;

} if(j==(forder)) /*forder-1*/

return(0);}for(j=0;j<forder;j++){ array[j][i]=array[j][i]-array[j][k];}

} } return(1);}

/*Program to find out if entered string contains a space character*/

#include <stdio.h>#include <conio.h>#include <ctype.h>space(char s);void main()

95

Page 96: C Programs

C Programs By VINOD

{

char s; clrscr(); printf("Enter string."); printf("String will be terminated if you press Ctrl-Z."); printf("STRING:- "); space(s); printf("HAVE A NICE DAY! BYE."); getch();}

space(char s) { int i; s=getchar(); for (i=0;(s=getchar())!=EOF;i++) { if (s==' ') { printf("String contains a space character."); break; } } if (s==EOF) printf("String does not contain a space character."); return(s); }

/*Program to find out the rightmost occurence of an input characterin an input string*/

#include <stdio.h>#include <conio.h>int strindex(char s[],char t);void main(){

char s[80],t; int a=0; clrscr(); printf("Enter main string(i.e. s):-"); gets(s); printf("Enter the character to be searched(i.e. t):- "); t=getchar(); a=strindex(s,t); if (a>=0)

96

Page 97: C Programs

C Programs By VINOD

printf("The required character is found at position %d.",a); else printf("The required character is not found in the string."); getch();}

int strindex(char s[],char t){ int i=0; for (i=strlen(s);i>=0;i--) { if (s[i]==t)

return(i); }if (i<0)

return(-1);}

/*Program to find the binary number has how many ones and zeros*/

#include<stdio.h>#include<conio.h>void main(){int n,x,a,b,s; clrscr(); a=0;b=0; printf("enter the binary no:"); scanf("%d",&n); s=n; while(n>0) { x=n%10; n=n/10; if(x==0) a++; else if(x==1) b++; } printf("the number is:%d",s); printf("the ones are:%d",b); printf("the zeros are:%d",a); getch(); }

/*Program to generate Fibonacci Series*/

#include <stdio.h>

void main(){ int OldNum, NewNum, FibNum, MaxNum;

97

Page 98: C Programs

C Programs By VINOD

clrscr(); printf("Generate Fibonacci Numbers till what number? "); scanf("%d", &MaxNum);

OldNum=0; NewNum=1; FibNum = OldNum + NewNum;

printf("%d, %d, %d, ", OldNum, NewNum, FibNum);

for(;;) { OldNum = NewNum; NewNum = FibNum; FibNum = OldNum + NewNum; if(FibNum > MaxNum) { printf("");

getch(); exit(0); } printf("%d, ", FibNum); }

getch();}

/*Program to multiply two 3x3 matrices*/

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

/*Program to multiply two 3*3 matrices*/

void main() { int a[3][3],b[3][3],c[3][3],i,j,k; clrscr();

printf("Enter elements of A:"); for(i=0;i<=2;i++) for(j=0;j<=2;j++) scanf("%d",&a[i][j]);

printf("Enter elements of B:"); for(i=0;i<=2;i++) for(j=0;j<=2;j++) scanf("%d",&b[i][j]);

printf("A:"); for(i=0;i<=2;i++) { for(j=0;j<=2;j++)

printf("%d ",a[i][j]);printf(""); /*To change line.*/

98

Page 99: C Programs

C Programs By VINOD

}

printf("B:"); for(i=0;i<=2;i++) { for(j=0;j<=2;j++) printf("%d ",b[i][j]); printf(""); } k=0; while(k<=2) { for(i=0;i<=2;i++) { int sum=0; for(j=0;j<=2;j++) sum=sum+a[i][j]*b[j][k]; c[i][k]=sum; } k++; } printf("Result: "); for(i=0;i<=2;i++) { for(j=0;j<=2;j++) printf("%d ",c[i][j]); printf(""); } getch();}

/*Program to perform functions of a calculator*/

#include<stdio.h>#include<conio.h>void main(){int i,d,k,a,r,h;char m='y';long s,n1,n2;clrscr();printf("calculation ?");scanf("%c",&m);while(m=='Y'||m=='y'){clrscr();printf("1.factorial\n2.addition\n3.subtraction\n4.multiplication\n5.division\n6.squares\n7.exit\nenter

your choice .......");scanf("%d",&d);while(d>7||d<1)scanf("%d",&d); switch (d)

99

Page 100: C Programs

C Programs By VINOD

{ case 1: clrscr();

printf("enter any positive manageable number\n"); scanf("%d",&a); while (a<0)

scanf("%d",&a); k=1; for(i=1;i<=a;i++)

k=k*i; printf("factorial is %d",k);getch(); break;

case 2: clrscr();

printf("enter any two numbers"); scanf(" %ld %ld",&n1,&n2); s=n1+n2; printf("sum of the input numbers is %ld",s); getch();

break; case 3:

clrscr(); printf("enter any number"); scanf("%ld,%ld",&n1,&n2); s=n1-n2; printf("the difference between the two numbers is %ld",s); getch(); break;

case 4: clrscr(); printf("enter any numbers which are to be multilied"); scanf(" %ld,%ld",&n1,&n2); s=n1*n2; printf("the product is %ld",s); getch(); break;

case 5: clrscr(); printf("enter dividend"); scanf("%d",&n1); printf("enter divisor "); scanf("%d",&n2); while (n2==0)

{ scanf("%d",&n1); scanf("%d",&n2); }

s=n1/n2; printf("the quotient is %d",s); getch(); break;

case 6: clrscr(); printf("enter the number whose square is to be found out");

100

Page 101: C Programs

C Programs By VINOD

scanf(" %d",&n1); s=n1*n1; printf("the square of the number is %d",s); getch(); break;

case 7: exit();

default: printf("Error");}printf("another calculation");scanf(" %c",&m);}}

/*Program to pick & display the largest element of an input matrix*/

#include <stdio.h>#include <conio.h>#include <math.h>#define MAXROWS 30#define MAXCOLS 30void largest(int a[][MAXCOLS],int nrows,int ncols);void readinput(int a[][MAXCOLS],int m,int n);

void main(){ int nrows,ncols; int a[MAXROWS][MAXCOLS]; clrscr();

printf("How many rows in the matrix? "); scanf("%d",&nrows); printf("How many columns in the matrix? "); scanf("%d",&ncols); printf("Table"); readinput(a,nrows,ncols);

largest(a,nrows,ncols); getch();}

void readinput(int a[][MAXCOLS],int m,int n) { int row,col; for (row=0;row<m;++row) { printf("Enter data for row no. %2d",row+1); for (col=0;col<n;++col) scanf("%d",&a[row][col]); } printf(" TABLE 1"); for (row=0;row<m;++row)

101

Page 102: C Programs

C Programs By VINOD

{ printf(""); for (col=0;col<n;++col) printf("%d%c",a[row][col],' '); } return; }

void largest(int a[][MAXCOLS],int m,int n) { int i,j,largest; largest = a[0][0]; for (i=0;i<m;++i) { for (j=0;j<n;++j) { if (a[i][j]>largest) largest=a[i][j]; } } printf("The largest element of the matrix is %d",largest); return; }

/*Program to print the ascii equivalent of all chararters in the entered string*/

#include <stdio.h>#include <conio.h>#include <ctype.h>int ascii_value(char c);void main(){

int i,a; char c; clrscr(); printf("Please enter a string."); printf("String will be terminated if you press Ctrl-Z."); printf("STRING:- "); for (i=0;(c=getchar())!=EOF;i++) { a=ascii_value(c); printf("%d%c",a,' '); } printf("are the ascii values of the characters of the entered string"); printf("respectively."); printf("HAVE A NICE DAY! BYE."); getch();}

int ascii_value(char c) {

102

Page 103: C Programs

C Programs By VINOD

int a; a=(int)c; return(a); }

/*Program. to find & replace any desired character from the input text.*/

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

void find_rep(void);

char c1,c2,a[80];void main(){ clrscr(); find_rep(); getch();

}/* Function to find & replace any text */void find_rep(void){ char c1,c2; char a[80]; int i,j,k; printf("Enter a line of text below:-"); printf("Line will be terminated by pressing ENTER.");printf("TEXT:- "); gets(a); printf("Enter the replaceable & replacing letter respectively:- "); scanf("%c%c%c",&c1,' ',&c2); for (j=0;j<80;j++) { if (a[j]==c1) a[j]=c2; } puts(a); printf("Here all %c are replaced by %c.",c1,c2); return;}

WORK OUT

/*Puzzle--finding the number*/

#include<stdio.h>#include<conio.h>#include<graphics.h>#include<dos.h>#include<math.h>

103

Page 104: C Programs

C Programs By VINOD

int mx,my,ans=0,p=4;

screen();void button();

/* 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).Therefore it will beplaced in 2,3 & 4 screen*/

int s1[]={16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};int s2[]={8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31};int s3[]={4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31};int s4[]={2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31};int s5[]={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31};int a1,a2,a3,a4,a5;

void main(){int gd=DETECT,gm;initgraph(&gd,&gm,"c:\tc\bgi");mouseini();showmp();action();getch();}

action(){ int ans=0; char st[10]; initialscreen(); 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,(my/4)+100,(mx/4)+235,(my/4)+140,"Play..")==0) { a1=screen(s1,16); a2=screen(s2,16); a3=screen(s3,16); a4=screen(s4,16); a5=screen(s5,16); ans=a1+a2+a3+a4+a5; result(ans); getch(); exit(); } }}initialscreen()

104

Page 105: C Programs

C Programs By VINOD

{mx=getmaxx(),my=getmaxy();setmp();setfillstyle(1,7);bar(mx/4,my/4,3*mx/4,3*my/4);setcolor(WHITE);line(mx/4,my/4,3*mx/4,my/4);line(mx/4,my/4,mx/4,3*my/4);setcolor(BLACK);line(mx/4,3*my/4,3*mx/4,3*my/4);line(3*mx/4,my/4,3*mx/4,3*my/4);setcolor(RED);outtextxy((mx/4)+40,(my/4)+30,"THINK A NUMBER BETWEEN 1-31");button((mx/4)+95,(my/4)+100,(mx/4)+235,(my/4)+140,"Play..");}screen(int *scr,int num){ int a,i,x1,y1;char st[10];mx=getmaxx(),my=getmaxy();setmp();setfillstyle(1,7); bar(mx/4,my/4,3*mx/4,3*my/4);setcolor(WHITE); line(mx/4,my/4,3*mx/4,my/4); line(mx/4,my/4,mx/4,3*my/4);setcolor(BLACK); line(mx/4,3*my/4,3*mx/4,3*my/4); line(3*mx/4,my/4,3*mx/4,3*my/4);setcolor(RED); outtextxy((mx/4)+9,(my/4)+5,"TELL ME WHETHER THE NUMBER IS PRESENT?"); button((3*mx/4)-40 ,(3*my/4)-20,(3*mx/4)-5 ,(3*my/4)-5,"yes"); button((3*mx/4)-80 ,(3*my/4)-20,(3*mx/4)-45 ,(3*my/4)-5,"no"); x1=(mx/4)+80; y1=(my/4)+65; for(i=0;i<num;i++) { a=scr[i]; /*To convert the integer into string and then displaying it on thegraphic mode*/ itoa(a,st,10); outtextxy(x1 ,y1,&st); x1+=50; if((i==3)||(i==7)||(i==11)) { y1=y1+30; x1=(mx/4)+80; } } /*We have already noted that the numbers are placed in screencorresponding to their binary value To find the number we can convert these binary numbers to integers*/ while(1) { if (click((3*mx/4)-40 ,(3*my/4)-20,(3*mx/4)-5 ,(3*my/4)-5,"yes")==0) {

105

Page 106: C Programs

C Programs By VINOD

ans=pow(2,p); p=p-1; return ans; } if (click((3*mx/4)-80 ,(3*my/4)-20,(3*mx/4)-45 ,(3*my/4)-5,"no")==0) { p=p-1; return 0; } }}result(int ans){ char st[10];mx=getmaxx(),my=getmaxy();setmp();setfillstyle(1,7);bar(mx/4,my/4,3*mx/4,3*my/4);setcolor(WHITE);line(mx/4,my/4,3*mx/4,my/4);line(mx/4,my/4,mx/4,3*my/4);setcolor(BLACK);line(mx/4,3*my/4,3*mx/4,3*my/4);line(3*mx/4,my/4,3*mx/4,3*my/4);setcolor(RED);if(ans==0) { outtextxy((mx/4)+110,(my/4)+45,"I DONT BELEIVE"); outtextxy((mx/4)+60,(my/4)+60,"YOU MIGHT BE WRONG SOMEWHERE"); } else { outtextxy((mx/4)+95,(my/4)+30,"THE NUMBER IS "); itoa(ans,st,10); outtextxy((mx/4)+205,(my/4)+30,st); }button((mx/4)+95,(my/4)+100,(mx/4)+235,(my/4)+140,"TRY AGAIN!");button((mx/4)+95,(my/4)+150,(mx/4)+235,(my/4)+190,"EXIT");while(1) { if (click((mx/4)+95,(my/4)+150,(mx/4)+235,(my/4)+190,"EXIT")==0) { closegraph(); restorecrtmode(); exit(); } if (click((mx/4)+95,(my/4)+100,(mx/4)+235,(my/4)+140,"TRY AGAIN!")==0) { p=4; action(); } }}void button(int x1,int y1,int x2,int y2,char str[]){ int xc,yc,i=0,l=0;

106

Page 107: C Programs

C Programs By VINOD

while(i<strlen(str)) { l+=4; i++; } xc=(x2-x1)/2+x1-l; yc=(y2-y1)/2+y1; unpress(x1,y1,x2,y2); settextstyle(0,0,0); setcolor(RED); outtextxy(xc,yc,str);}unpress(int x1,int y1,int x2,int y2){setlinestyle(0,1,1);setfillstyle(1,7);bar(x1,y1,x2,y2);setcolor(WHITE);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(0);line(x1,y2,x2,y2);line(x2,y1,x2,y2);return 0;}press(int x1,int y1,int x2,int y2){setlinestyle(0,1,1);setfillstyle(1,7);bar(x1,y1,x2,y2);setcolor(0);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(WHITE);line(x1,y2,x2,y2);line(x2,y1,x2,y2);return 0;}mouseini(){union REGS i,o;i.x.ax=0;int86(0x33,&i,&o);return(o.x.ax);}showmp(){union REGS i,o;i.x.ax=1;int86(0x33,&i,&o);return 0;}hidemp(){union REGS i,o;

107

Page 108: C Programs

C Programs By VINOD

i.x.ax=2;int86(0x33,&i,&o);return 0;}

getmp(int *button,int *x,int *y){union REGS i,o;i.x.ax=3;int86(0x33,&i,&o);*button=o.x.bx;*x=o.x.cx;*y=o.x.dx;return 0;}setmp(){union REGS i,o;i.x.ax=4;i.x.cx=(3*mx/4)+20;i.x.dx=(3*my/4)+20;int86(0x33,&i,&o);}click(int x1,int y1,int x2,int y2,char str[]){int button,x,y;int xc,yc,i=0,l=0;while(i<strlen(str)) { l+=4; i++; }xc=(x2-x1)/2+x1-l;yc=(y2-y1)/2+y1;

getmp(&button,&x,&y);if( (x>x1 && x<x2) && (y>y1 && y<y2) && button==1){ hidemp(); press(x1,y1,x2,y2); setcolor(RED); settextstyle(0,0,0); outtextxy(xc,yc,str); showmp(); while((button==1)) getmp(&button,&x,&y); hidemp(); unpress(x1,y1,x2,y2); showmp(); setcolor(RED); settextstyle(0,0,0); outtextxy(xc,yc,str); for(i=50;i<500;i=i+50) { delay(10);

108

Page 109: C Programs

C Programs By VINOD

sound(i+200); } showmp(); nosound(); setcolor(RED); settextstyle(0,0,0); outtextxy(xc,yc,str); return 0;}else return 1;}

/*Pyramid of Numbers*/

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

int pyramid( int length ) {

int line = 1;int j = 1, i, k = length;

while( length-- ) {

if( j == 1 ) {for( i = 1; i <= length + 5; i++ )

printf( " " );printf( "%d", j++ );k--;line++;

}

else if( i % 2 ){for( i = 1; i <= length + 5; i++ )

printf( " " );for( i = 1; i <= line; i++ )

printf( "%d ", ( j++ % 10 ) );printf( "" );line++;k--;

}

else {for( i = 1; i <= length + 5 ; i++ )

printf( " " );for( i = 1; i <= line; i++ )

printf( "%d ", ( j++ % 10 ) );printf( "" );line++;k--;

}}

return 0;

109

Page 110: C Programs

C Programs By VINOD

}

int main( ) {

int length;

printf( "Enter the list length" );scanf( "%d", &length );

pyramid( length );getch( );return 0;

}

/*Square root of a number without using Built-In Function*/

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

void main(){ double n,g1,g2; int flag=0; clrscr(); printf("Enter the no.: "); scanf("%lf",&n); if(n<0) { n=-n; flag=1; } else if(n==0) { printf("The root of %6.4lf is",n); textcolor(GREEN); cprintf(" %6.4lf",g2); getch(); exit(0); } g2=n/2; do { g1=g2; g2=(g1+n/g1)/2; } while((g1-g2)!=0); if(flag==1) { printf("The root of %6.4lf is",-n); textcolor(GREEN); cprintf(" +/- %6.4lf i",g2); } else { printf("The root of %6.4lf is",n);

110

Page 111: C Programs

C Programs By VINOD

textcolor(GREEN); cprintf(" +/- %6.4lf",g2); } getch();}

WORK OUT

/*system Clock and date*/

#include<stdio.h>#include<conio.h>#include<graphics.h>#include<process.h>#include <dos.h>#include <dir.h>

union REGS i,o;int button,p,q;

main(){int gd = DETECT,gm;int maxx,maxy,x,y,button,i,j,x2,x1,y2,y1;int cor[60][2],f=1,hour,min,sec,l,dat,mont,yea;struct arccoordstype arcinfo;struct time t;struct date d;char mm[80],mf[80],m[50],n[5];charmon[12][4]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};initmouse();showmouseptr();initgraph(&gd,&gm,"c:\turboc\bgi.arc");maxx=getmaxx();maxy=getmaxy();/*textcolor(0);*/setviewport(1,1,getmaxx()-2,getmaxy()-2,1);showmouseptr();restrictmouseptr(350,20,600,70);circle(maxx/2,maxy/2,100);putpixel(maxx/2,maxy/2,3);setfillstyle(0,0);j=90;setcolor(0);cleardevice();setfillstyle(1,14);bar(390,55,440,70);setfillstyle(1,14);bar(460,55,500,70);setfillstyle(1,14);

111

Page 112: C Programs

C Programs By VINOD

bar(390,30,460,45);setfillstyle(1,14);bar(466,30,540,45);j=30;setfillstyle(1,12);bar(180,100,465,387);setfillstyle(1,0);bar(185,104,460,383);while(f<13){if (i<=90) {i=90-j;} else { i=360-(j-90);}setcolor(0);arc(maxx/2,maxy/2,90,i,125);getarccoords(&arcinfo);setcolor(14);settextstyle(DEFAULT_FONT, HORIZ_DIR,2);if (f<=5) {sprintf(n,"%d",f);outtextxy(arcinfo.xend+2,arcinfo.yend,n);}else if ((f>=7)&&(f<12)){sprintf(n,"%d",f);outtextxy(arcinfo.xend-7,arcinfo.yend,n);}else if(f==12){sprintf(n,"%d",f);outtextxy(arcinfo.xstart-10,arcinfo.ystart,n);}else if (f==6) {sprintf(n,"%d",f);outtextxy(arcinfo.x-17,arcinfo.y+120,n);}j+=30;f++;}setcolor(13);sprintf(mm,"Exit");outtextxy(550,35,mm);settextstyle(DEFAULT_FONT,0,1);sprintf(mm,"Done by:");outtextxy(400,435,mm);settextstyle(DEFAULT_FONT, HORIZ_DIR,2);sprintf(mm,"Ajith.V.V");outtextxy(470,445,mm);

settextstyle(DEFAULT_FONT, HORIZ_DIR,0);outtextxy(400,60,"Time Date");

sprintf(mm,"SET-TIME");outtextxy(395,35,mm);sprintf(mm,"SET-DATE");outtextxy(470,35,mm);f=0;while(1){getmousepos(&button,&p,&q);getdate(&d);gettime(&t);/*outer*/setfillstyle(1,15);pieslice(maxx/2,maxy/2,0,360,5);setfillstyle(1,12);bar(180,100,184,387);bar(461,100,465,387);

112

Page 113: C Programs

C Programs By VINOD

bar(180,100,465,105);bar(180,385,465,387);bar(200,390,445,400);bar(180,400,465,405);/*hour*/if (t.ti_hour>13) {t.ti_hour = t.ti_hour - 12;}if (t.ti_min==0) {i=(t.ti_hour*30);} else{i=((t.ti_hour*30)+((t.ti_min/12)*6));}if (i>=90) {j=360-(i-90);}else {j=90-i;}textcolor(0);setcolor(0);arc(maxx/2,maxy/2,j,90,50);getarccoords(&arcinfo);if (((t.ti_hour==0)||(t.ti_hour==12))&&(t.ti_min<=11)){setcolor(0);line(maxx/2,maxy/2,x1,y1);setcolor(3);line(maxx/2,maxy/2,maxx/2,maxy/2-50);x1=0;y1=0;x1=maxx/2;y1=maxy/2-50;}else{setcolor(0);line(maxx/2,maxy/2,x1,y1);setcolor(3);line(maxx/2,maxy/2,arcinfo.xstart,arcinfo.ystart);x1=arcinfo.xstart;y1=arcinfo.ystart;}/*hour*//*minutr*/i=(t.ti_min*6);if (i>=90) {j=360-(i-90);}else {j=90-i;}textcolor(0);setcolor(0);arc(maxx/2,maxy/2,j,90,90);getarccoords(&arcinfo);if (t.ti_min==0){setcolor(0);line(maxx/2,maxy/2,x2,y2);setcolor(2);line(maxx/2,maxy/2,maxx/2,maxy/2-80);x2=0;y2=0;x2=maxx/2;y2=maxy/2-80;}else{setcolor(0);

113

Page 114: C Programs

C Programs By VINOD

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

114

Page 115: C Programs

C Programs By VINOD

}

if (l==3){gotoxy(38,20);printf("%d:%d:%d",t.ti_hour,t.ti_min,t.ti_sec);}

press();getmousepos(&button,&p,&q);if ((p>=460)&&(p<=500)&&(q>=55)&&(q<=70)&&((button & 1)==1)){f=f^1;if (f==1){l=5;}else{l=0;gotoxy(36,12);printf(" ");}}

if (l==5){gotoxy(36,12);printf("%d,%s %d ",d.da_day,mon[d.da_mon-1],d.da_year);}

if (t.ti_min==0){sound(2000);}if (t.ti_sec>=2){nosound();}press();getmousepos(&button,&p,&q);if ((p>=550)&&(p<=650)&&(q>=33)&&(q<=50)&&((button & 1)==1)) {goto end;}/*set time*/if ((p>=390)&&(p<=460)&&(q>=30)&&(q<=45)&&((button & 1)==1)){gotoxy(1,22);printf("Enter :");gotoxy(1,23);printf("Hour[24]:");scanf("%d",&hour);gotoxy(1,24);printf("Minute :");scanf("%d",&min);gotoxy(1,25);printf("Second :");scanf("%d",&sec);if (hour!=24)

115

Page 116: C Programs

C Programs By VINOD

{t.ti_hour = hour;} else {t.ti_hour = 0;}t.ti_min = min;t.ti_sec = sec;settime(&t);gotoxy(1,22);printf(" ");gotoxy(1,23);printf(" ");gotoxy(1,24);printf(" ");gotoxy(1,25);printf(" ");}/*set date*/if ((p>=350)&&(p<=510)&&(q>=35)&&(q<=45)&&((button & 1)==1)){gotoxy(1,22);printf("Enter :");gotoxy(1,23);printf("date :");scanf("%d",&dat);gotoxy(1,24);printf("Month :");scanf("%d",&mont);gotoxy(1,25);printf("Year :");scanf("%d",&yea);d.da_day=dat;d.da_mon=mont;d.da_year=yea;setdate(&d);gotoxy(1,22);printf(" ");gotoxy(1,23);printf(" ");gotoxy(1,24);printf(" ");gotoxy(1,25);printf(" ");}/*while end*/}end:closegraph();restorecrtmode();/*program end*/return 0;}

initmouse(){i.x.ax = 0;int86(0x33,&i,&o);return (o.x.ax);}

116

Page 117: C Programs

C Programs By VINOD

showmouseptr(){i.x.ax = 1;int86(0x33,&i,&o);return 0;}hidemouseptr(){i.x.ax = 2;int86(0x33,&i,&o);return 0;}

restrictmouseptr(int x1,int y1,int x2,int y2){i.x.ax = 7;i.x.cx = x1;i.x.dx = x2;int86 (0x33,&i,&o);i.x.ax = 8;i.x.cx = y1;i.x.dx = y2;int86 (0x33,&i,&o);return 0;}

getmousepos(int *button,int *x,int *y){i.x.ax = 3;int86 (0x33,&i,&o);*button = o.x.bx;*x=o.x.cx;*y=o.x.dx;return 0;}

press(){while ((button & 1)==1){getmousepos(&button,&p,&q);}return 0;}

This program prints the Fibonacci series

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

int i,j,k,n;clrscr();i=0;j=1;

117

Page 118: C Programs

C Programs By VINOD

printf("%d %d ",i,j);for(n=0;n<=5;n++){k=i+j;i=j;j=k;printf("%d ",k);}getch();

}

/*Understanding IVT table*/

/* understanding ivt table*/#include<stdio.h>#include<dos.h>main(){ unsigned long far *address = (unsigned long far *)0x00000000; unsigned long intadd[256]; unsigned int segment, offset; int i; FILE *fp; fp = fopen("IVT.txt", "wb"); for(i = 0; i < 256; i++) { intadd[i] = *(address++); segment = FP_SEG(intadd[i]); offset = FP_OFF(intadd[i]); fprintf(fp, "interrupt %3X : vector %Fp(hex) : %lu(dec)",i, intadd[i], (unsigned long)segment * 16 + offset); } fclose(fp);getch();}

/*Vertical Histogram*/

#include<stdio.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];int i,c,j,nc,nw;

for(i=0;i<MAXNO;++i)word[i]=0;

nc = nw = 0;

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

118

Page 119: C Programs

C Programs By VINOD

++nc;if( c ==' ' || c ==' '|| c ==' '){

word[nw] = nc -1; /* -1 for excluding the space in the word length */

++nw;nc = 0; /* resetting the word-length for the next word

*/}

}

for( i = MAXWL; i >= 1; --i){

for(j=0;j <= nw;++j){

if( i <= word[j])putchar('*');

elseputchar(' ');

}putchar(' ');}

getch();}

Write a program to find permutation

#include<stdio.h>#include<stdlib.h>int lev=-1,n,val[50],a[50];void main(){ int i,j; clrscr(); printf("Enter howmany numbers"); scanf("%d",&n); for(i=0;i<n;i++) { val[i]=0; j=i+1; scanf("%d",&a[j]); } visit(0); getch();}visit(int k){ int i; val[k]=++lev; if(lev==n) {

119

Page 120: C Programs

C Programs By VINOD

for(i=0;i<n;i++) printf("%2d",a[val[i]]); printf(" "); } for(i=0;i<n;i++) if(val[i]==0) visit(i); lev--; val[k]=0;}

WORK OUT/*Simple Account software*/

#include<graphics.h>#include<dos.h>#include<alloc.h>#include<stdio.h>#include<string.h>

union REGS i,o;char *menu[]={"1.Add Records","2.Show Records","3.Modify Records","4.Del Records","5.Search

Record","6.Exit"};

main(){ int gd=DETECT,gm,choice=1,width=0,i,count,sr=0; char **buffer; FILE *m,*t; char sname[20]; long int size; char mrec;

struct cust{ char name[20]; int accno; float balance;};

struct cust s;

m=fopen("C:\record.txt","rb+");

if(m==NULL) {

t=fopen("C:\record.txt","wb+");

if(t==NULL){ printf("Error in opening file "); exit();

120

Page 121: C Programs

C Programs By VINOD

} } size=sizeof(s); initgraph(&gd,&gm,"C:\turboc\Bgi.arc");

setbkcolor(1); setcolor(11); if(initmouse()==0) { printf("Mouse driver not loaded..."); exit(); }

count=sizeof(menu)/sizeof(char *); settextstyle(TRIPLEX_FONT,0,3); displaymenu(menu,count,10,10);

for(i=0;i<count;i++) { if(textwidth(menu[i])>width)

width=textwidth(menu[i]); }

/* movemouseptr(&x1,&y1);*/

buffer=malloc(sizeof(menu)); savemenu(menu,buffer,width,count,10,10); showmouseptr(); while (1) { displaymenu(menu,count,10,10);

choice=getresponse(menu,buffer,width,count,10,10);gotoxy(50,15);

hidemouseptr(); switch (choice)

{case 1 : cleardevice(); fseek(m,0,SEEK_END); mrec='y'; gotoxy(1,1); while(mrec=='y') { printf("Enter the Name of the Custumer "); scanf("%s",s.name); printf("Enter the Acc.no of the Custumer "); scanf("%d",&s.accno); printf("Enter the Balance of the Custumer "); scanf("%f",&s.balance);

fwrite(&s,size,1,m); printf("Are there more Records (Y/N)"); fflush(stdin); mrec=getche(); } printf("Press any key to go back to menu");

121

Page 122: C Programs

C Programs By VINOD

cleardevice(); break;

case 2: cleardevice(); rewind(m); gotoxy(1,1); printf("Name Acc.No Ammount Due"); sr=0; if(fread(&s,size,1,m)==1) { rewind(m); while(fread(&s,size,1,m)==1) { printf("%30s%12d%23.2f",s.name,s.accno,s.balance); sr++; } } elseprintf(" There is no record to Display"); printf("There are %d Records",sr); printf("Press any key to go back to menu"); getch(); cleardevice(); break;

case 3: clearviewport(); mrec='y'; gotoxy(1,1); while(mrec=='y') { printf("Enter the name of Customer whose rec. is to be modified"); scanf("%s",sname); /* gets(sname);*/ rewind(m); while (fread(&s,size,1,m)==1) { sr=0; if( strcmp (s.name,sname)==0) { sr=1;/* printf("Enter new name,Acc.no,Balance ");*//* scanf("%s%d%f",s.name,&s.rollno,&s.percent);*/ printf("Enter the new Name of the Custumer "); scanf("%s",s.name); /*gets(s.name);*/

printf("Enter the new Acc.no of the Custumer "); scanf("%d",&s.accno); printf("Enter the new Balance of the Custumer "); scanf("%f",&s.balance);

fseek(m,-size,SEEK_CUR); fwrite(&s,size,1,m); break; } }

122

Page 123: C Programs

C Programs By VINOD

if(sr==0)printf("Record %s is not found",sname); printf("Modify more records (Y/N)"); fflush(stdin); mrec=getche();

}clearviewport();break;case 4: clearviewport(); mrec='y'; gotoxy(1,1); while(mrec=='y') { printf("Enter the name of the Customer to delete the rec "); scanf("%s",sname); /* gets(sname);*/ t=fopen("C:\stemp.txt","wb");

rewind (m);while(fread(&s,size,1,m)==1){ if(strcmp(s.name,sname)!=0)fwrite(&s,size,1,t);} fclose(m); fclose(t); remove("C:\record.txt"); rename("C:\stemp.txt","C:\record.txt");

m=fopen("C:\record.txt","rb+");

printf("Delete more records (Y/N)"); fflush(stdin); mrec=getche(); } clearviewport();/* displaymenu(menu,count,10,10);*//*getch();*//*choice=getresponse(menu,buffer,width,count,10,10);*/ break;case 5: clearviewport(); mrec='y'; gotoxy(1,1); while(mrec=='y') { printf("Enter the name of Customer whose rec. is to be Searched"); scanf("%s",sname);/*gets(sname);*/ rewind(m); while (fread(&s,size,1,m)==1) { sr=0; if( strcmp (s.name,sname)==0) { /* printf("Enter new name,Acc.no,Balance");*/ /* scanf("%s%d%f",s.name,&s.rollno,&s.percent);*/

123

Page 124: C Programs

C Programs By VINOD

/* fseek(m,-size,SEEK_CUR);*//* fwrite(&s,size,1,m);*/ printf("Record found"); printf("Name Acc.No Ammount Due"); printf("%30s%12d%23.2f",s.name,s.accno,s.balance); sr=1; getch(); break; } } if(sr==0) printf("Record %s is not found",sname); printf("Search more records (Y/N)"); fflush(stdin); mrec=getche();

}clearviewport();break;

case 6: fclose(m); exit();

} showmouseptr(); }

getch();}

displaymenu(char **menu,int count,int x1,int y1){ int i,h;

h=textheight(menu[0]);

for(i=0;i<count;i++) outtextxy(x1,y1+i*(h+5),menu[i]);}

savemenu (char **menu,char **buffer,int width,int count,int x1,int y1){ int i,x2,yy1,yy2,area,h;

h=textheight(menu[0]);

for(i=0;i<count;i++) { x2=x1+width; yy1=y1+i*(h+5); yy2=y1+(i+1)*(h+5);

area=imagesize(x1,yy1,x2,yy2); buffer[i]=malloc(area); getimage(x1,yy1,x2,yy2,buffer[i]);

124

Page 125: C Programs

C Programs By VINOD

}}

getresponse(char **menu,char **buffer,int width,int count,int x1,int y1){ int choice=1,prevchoice=0,x,y,x2,y2,button; int in,i,h;

h=textheight(menu[0]); y2=y1+count*(h+5); x2=x1+width; rectangle(x1-5,y1-5,x2+5,y2+5);

while(1) {

getmousepos(&button,&x,&y);

if (x>=x1&&x<=x2&&y>=y1&&y<=y2) { in=1;

for(i=1;i<=count;i++) { if(y<=y1+i*(h+5)) { choice=i;break; } }

if(prevchoice!=choice) {hidemouseptr();highlight(buffer,choice,h,x1,y1);

if(prevchoice) dehighlight(buffer,prevchoice,h,x1,y1);

prevchoice=choice; showmouseptr(); }if((button & 1)==1) {while ((button & 1)==1) getmousepos(&button,&x,&y);

if(x>=x1&&x<=x2&&y>=y1&&y<=y2)return(choice); }}

else { if( in ==1) {

in=0;

125

Page 126: C Programs

C Programs By VINOD

prevchoice=0;hidemouseptr();dehighlight(buffer,choice,h,x1,y1);showmouseptr();

} } }}

highlight(char **buffer,int ch,int h,int x1,int y1){ putimage(x1,y1+(ch-1)*(h+5),buffer[ch-1],NOT_PUT);}

dehighlight(char **buffer,int ch,int h,int x1,int y1){ putimage(x1,y1+(ch-1)*(h+5),buffer[ch-1],COPY_PUT);}

/* initmouse */initmouse(){ i.x.ax=0; int86 (0x33,&i,&o); return(o.x.ax);}

/* displays mouse pointer */showmouseptr(){ i.x.ax=1; int86(0x33,&i,&o);}

hidemouseptr(){ i.x.ax=2; int86(0x33,&i,&o);}

/*gets mouse coordinates and button status*/

getmousepos(int *button,int *x,int *y){ i.x.ax=3; int86(0x33,&i,&o); *button=o.x.bx; *x=o.x.cx; *y=o.x.dx;}

movemouseptr(int *x,int *y){

126

Page 127: C Programs

C Programs By VINOD

i.x.ax=4; int86(0x33,&i,&o); o.x.cx=*x; o.x.dx=*y; return 0;}

Arrays and pointers in C ======================== (Thanks a lot to Steve Summit for the very illuminating comments, 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. The seemingly unrelated C rules are explained as an attempt to unify arrays and pointers, replacing arrays and the basic array equation by a new notation and special rules (see below).

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.

2) Show possible workarounds for the lack of adjustable arrays, one of C technical shortcomings. 3) Show an interesting method of array implementation.

The C language as a "portable assembler" ---------------------------------------- Older operating systems and other system software were written in assembly language. CPUs were slow and memories very small, and only assembly language could generate the tight code needed.

However, assembly is difficult to maintain and by definition not portable, so the advantages of a High Level Language designed for system programming were clear. Improvements in hardware and compiler technology made C a success.

Pointers and pointer operators ------------------------------ FORTRAN imposes a major restriction on the programmer, you can reference only named memory locations, i.e. Fortran variables. Pointers make it possible, like in assembly, to reference in a useful way any memory location.

A pointer is a variable suitable for keeping memory addresses of other variables, the values you assign to a pointer are memory addresses of other variables (or other pointers).

How useful are pointers for scientific programming? Probably

127

Page 128: C Programs

C Programs By VINOD

much less than C fans think, few algorithms used in scientific require pointers. It is well-known that having unrestricted pointers in a programming language makes it difficult for the compiler to generate efficient code.

C pointers are characterized by their value and data-type. The value is the address of the memory location the pointer points to, the type determines how the pointer will be incremented/decremented in pointer (or subscript) arithmetic (see below).

Arrays in C and the array equation ---------------------------------- We will use 2D arrays in the following text instead of general N-dimensional arrays, they can illustrate the subtle points involved with using arrays and pointers in C, and the arithmetic will be more manageable.

A 2D array in C is treated as a 1D array whose elements are 1D arrays (the rows).

For example, a 4x3 array of T (where "T" is some data type) may be declared by: "T mat[4][3]", 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, 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, it is the connection between the

128

Page 129: C Programs

C Programs By VINOD

abstract data-type and its implementation. In Fortran (and other languages) it is "hidden" from the programmer, the compiler automatically "plants" the necessary code whenever an array reference is made.

2) For higher-dimensional arrays the equation gets more and more complicated. In some programming languages an arbitrary limit on the dimension is imposed, e.g. Fortran arrays can be 7D at most.

3) Note that it's more efficient to compute the array equation "iteratively" - not using the distributive law to eliminate the parentheses (just count the arithmetical operations in the first two versions of the array equation above). The K&R method (see below) works iteratively.

It reminds one of Horner's Rule for computing a polynomial iterativly, e.g.

a * x**2 + b * x + c = (a * x + b) * x + c

computing the powers of x is eliminated in this way.

4) The number of rows doesn't enter into the array equation, you don't need it to compute the address of an element. That is the reason you don't have to specify the first dimension in a routine that is being passed a 2D array, just like in Fortran's assumed-size arrays.

The K&R method of reducing arrays to pointers --------------------------------------------- K&R tried to create a unified treatment of arrays and pointers, one that would expose rather than hide the array equation in the compiler's code. They found an elegant solution, albeit a bit complicated. 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.

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 function "size()" returns object's sizes.

3) The famous "decay convention": an array is treated as a pointer that points to the first element of the array.

The decay convention shouldn't be applied more than once to the same object.

4) Taking a subscript with value i is equivalent to the operation: "pointer-add i and then

129

Page 130: C Programs

C Programs By VINOD

type-dereference the sum", i.e.

xxx[i] = *(xxx # i)

When rule #4 + rule #3 are applied recursively (this is the case of a multi-dimensional array), only the data type is dereferenced and not the pointer's value, except on the last step.

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)

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". So we get the first two terms of the array equation.

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".

mat[i][j] = *((mat + i * sizeof(row)) # j) ^^^^^^^^^^^^^^^^^^^^^^^ Row of T

We have now one pointer addition left, using again the "decay convention", the 1D array "row of T" becomes a pointer to its first element, i.e. "pointer to T". We perform the pointer addition, 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, so we can write:

address(mat[i][j]) = address(mat[0][0]) + i * sizeof(row) + j * sizeof(T)

This is exactly the array equation. QED

130

Page 131: C Programs

C Programs By VINOD

Why a double pointer can't be used as a 2D array? ------------------------------------------------- This is a good example, although the compiler may not complain, it is wrong to declare: "int **mat" and then use "mat" as a 2D array. These are two very different data-types and using them you access different locations in memory. On a good machine (e.g. VAX/VMS) this mistake aborts the program with a "memory access violation" error.

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, so a 2D array is NOT equivalent to a double pointer. A "pointer to pointer of T" can't serve as a "2D array of T". The 2D array is "equivalent" to a "pointer to row of T", and this is very different from "pointer to pointer of T".

When a double pointer that points to the first element of an array, is used with subscript notation "ptr[0][0]", it is fully dereferenced 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()

131

Page 132: C Programs

C Programs By VINOD

{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 &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++){

132

Page 133: C Programs

C Programs By VINOD

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);

}

/* 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: ");

133

Page 134: C Programs

C Programs By VINOD

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. */

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++)

134

Page 135: C Programs

C Programs By VINOD

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]; for (i = 0 ; i < 3 ; i++) index[i] = (short *)mat + 3*i;

printf(" Declare as single-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;}

135