C / C++ SOURCE CODES
PROGRAMME FOR E.G. OF WIDTH AND SETEW FUNCTIONS
//e.g. of width and setew function...
#include <iostream.h>
#include <iomanip.h>
void main ()
{
int i;
cout << "A list of numbers :" << endl;
for (i = 1; i <= 1024; i *= 2)
{
cout.width (7);
cout << i << endl;
}
cout << "A table of numbers :" << endl;
for (i = 0; i <= 4; i++)
{
cout << setw(3) << i << setw(5) << i * i * i << endl;
}
}
//e.g. of width and setew function...
#include <iostream.h>
#include <iomanip.h>
void main ()
{
int i;
cout << "A list of numbers :" << endl;
for (i = 1; i <= 1024; i *= 2)
{
cout.width (7);
cout << i << endl;
}
cout << "A table of numbers :" << endl;
for (i = 0; i <= 4; i++)
{
cout << setw(3) << i << setw(5) << i * i * i << endl;
}
}
A PROGRAM THAT READS FROM A CHARACTER STRING
//A program that reads from a character string :
#include <iostream.h>
#include <strstrea.h>
#include <string.h>
void main ()
{
char a[1024];
istrstream b(a, 1024);
strcpy (a, "45.656");
double k, p;
b.seekg(0); // Start from first character.
b >> k;
k = k + 1;
cout << k << endl;
strcpy (a, "444.23 56.89");
b.seekg(0);
b >> k >> p;
cout << k << ", " << p + 1 << endl;
}
//A program that reads from a character string :
#include <iostream.h>
#include <strstrea.h>
#include <string.h>
void main ()
{
char a[1024];
istrstream b(a, 1024);
strcpy (a, "45.656");
double k, p;
b.seekg(0); // Start from first character.
b >> k;
k = k + 1;
cout << k << endl;
strcpy (a, "444.23 56.89");
b.seekg(0);
b >> k >> p;
cout << k << ", " << p + 1 << endl;
}
HERE IS A PROGRAM THAT WRITES INSIDE A CHARACTER ARRAY
//Here is a program that writes inside a character array :
#include <iostream.h>
#include <strstrea.h>
#include <string.h>
#include <math.h>
void main ()
{
char a[1024];
ostrstream b(a, 1024);
b.seekp(0); // Start from first char.
b << "2 + 2 = " << 2 + 2 << ends; // ( ends, not endl )
// ends is simply the
// null character '\0'
cout << a << endl;
double v = 2;
strcpy (a, "A sinus : ");
b.seekp(strlen (a));
b << "sin (" << v << ") = " << sin(v) << ends;
cout << a << endl;
}
//Here is a program that writes inside a character array :
#include <iostream.h>
#include <strstrea.h>
#include <string.h>
#include <math.h>
void main ()
{
char a[1024];
ostrstream b(a, 1024);
b.seekp(0); // Start from first char.
b << "2 + 2 = " << 2 + 2 << ends; // ( ends, not endl )
// ends is simply the
// null character '\0'
cout << a << endl;
double v = 2;
strcpy (a, "A sinus : ");
b.seekp(strlen (a));
b << "sin (" << v << ") = " << sin(v) << ends;
cout << a << endl;
}
programme to show that.a class can be derived from more than 1 base classes
//a class can be derived from more than 1 base classes
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double surface()
{
return fabs (x * y);
}
};
class number
{
public:
double z;
number (double a)
{
z = a;
}
int is_negative ()
{
if (z < 0) return 1;
else return 0;
}
};
class trivector : public vector, public number
{
public:
trivector(double a=0, double b=0, double c=0) : vector(a,b), number(c)
{
} // The trivector constructor calls the vector
// constructor, then the number constructor,
// and in this example does nothing more.
double volume()
{
return fabs (x * y * z);
}
};
void main()
{
trivector a(2, 3, -4);
cout << a.volume() << endl;
cout << a.surface() << endl;
cout << a.is_negative() << endl;
}
//a class can be derived from more than 1 base classes
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double surface()
{
return fabs (x * y);
}
};
class number
{
public:
double z;
number (double a)
{
z = a;
}
int is_negative ()
{
if (z < 0) return 1;
else return 0;
}
};
class trivector : public vector, public number
{
public:
trivector(double a=0, double b=0, double c=0) : vector(a,b), number(c)
{
} // The trivector constructor calls the vector
// constructor, then the number constructor,
// and in this example does nothing more.
double volume()
{
return fabs (x * y * z);
}
};
void main()
{
trivector a(2, 3, -4);
cout << a.volume() << endl;
cout << a.surface() << endl;
cout << a.is_negative() << endl;
}
programme for TRI-VECTOR CONSTRUCTOR
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
virtual double module()
{
return sqrt (x*x + y*y);
}
};
class trivector : public vector
{
public:
double z;
trivector (double m = 0, double n = 0, double p = 0)
{
x = m; // Just for the game,
y = n; // here I do not call the vector
z = p; // constructor and I make the
} // trivector constructor do the
// whole job. Same result.
double module ()
{
return sqrt (x*x + y*y + z*z);
}
};
void test (vector &k)
{
cout << "Test result : " << k.module() << endl;
}
void main()
{
vector a (4, 5);
trivector b (1, 2, 3);
cout << "a (4, 5) b (1, 2, 3)" << endl << endl;
vector *r;
r = &a;
cout << "module of vector a : " << r->module() << endl;
r = &b;
cout << "module of trivector b : " << r->module() << endl;
test (a);
test (b);
vector &s = b;
cout << "module of trivector b : " << s.module() << endl;
}
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
virtual double module()
{
return sqrt (x*x + y*y);
}
};
class trivector : public vector
{
public:
double z;
trivector (double m = 0, double n = 0, double p = 0)
{
x = m; // Just for the game,
y = n; // here I do not call the vector
z = p; // constructor and I make the
} // trivector constructor do the
// whole job. Same result.
double module ()
{
return sqrt (x*x + y*y + z*z);
}
};
void test (vector &k)
{
cout << "Test result : " << k.module() << endl;
}
void main()
{
vector a (4, 5);
trivector b (1, 2, 3);
cout << "a (4, 5) b (1, 2, 3)" << endl << endl;
vector *r;
r = &a;
cout << "module of vector a : " << r->module() << endl;
r = &b;
cout << "module of trivector b : " << r->module() << endl;
test (a);
test (b);
vector &s = b;
cout << "module of trivector b : " << s.module() << endl;
}
A class may be DERIVED from another class.
//A class may be DERIVED from another class. The new class INHERITS
//the variables and methods of the BASE CLASS. Additional variables
// and/or methods can be added :
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double module()
{
return sqrt (x*x + y*y);
}
double surface()
{
return x * y;
}
};
class trivector : public vector // trivector is derived from vector
{
public:
double z; // added to x and y from vector
trivector (double m=0, double n=0, double p=0) : vector (m, n)
{
z = p; // Vector constructor will
} // be called before trivector
// constructor, with parameters
// m and n.
trivector (vector a) // What to do if a vector is
{ // cast to a trivector
x = a.x;
y = a.y;
z = 0;
}
double module () // define module() for trivector
{
return sqrt (x*x + y*y + z*z);
}
double volume ()
{
return this->surface() * z; // or x * y * z
}
};
void main()
{
vector a (4, 5);
trivector b (1, 2, 3);
cout << "a (4, 5) b (1, 2, 3) *r = b" << endl << endl;
cout << "Surface of a : " << a.surface() << endl;
cout << "Volume of b : " << b.volume() << endl;
cout << "Surface of base of b : " << b.surface() << endl;
cout << "Module of a : " << a.module() << endl;
cout << "Module of b : " << b.module() << endl;
cout << "Module of base of b : " << b.vector::module() << endl;
trivector k;
k = a; // thanks to trivector(vector) definition
// copy of x and y, k.z = 0
vector j;
j = b; // copy of x and y. b.z leaved out
vector *r;
r = &b;
cout << "Surface of r : " << r->surface() << endl;
cout << "Module of r : " << r->module() << endl;
}
//A class may be DERIVED from another class. The new class INHERITS
//the variables and methods of the BASE CLASS. Additional variables
// and/or methods can be added :
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double module()
{
return sqrt (x*x + y*y);
}
double surface()
{
return x * y;
}
};
class trivector : public vector // trivector is derived from vector
{
public:
double z; // added to x and y from vector
trivector (double m=0, double n=0, double p=0) : vector (m, n)
{
z = p; // Vector constructor will
} // be called before trivector
// constructor, with parameters
// m and n.
trivector (vector a) // What to do if a vector is
{ // cast to a trivector
x = a.x;
y = a.y;
z = 0;
}
double module () // define module() for trivector
{
return sqrt (x*x + y*y + z*z);
}
double volume ()
{
return this->surface() * z; // or x * y * z
}
};
void main()
{
vector a (4, 5);
trivector b (1, 2, 3);
cout << "a (4, 5) b (1, 2, 3) *r = b" << endl << endl;
cout << "Surface of a : " << a.surface() << endl;
cout << "Volume of b : " << b.volume() << endl;
cout << "Surface of base of b : " << b.surface() << endl;
cout << "Module of a : " << a.module() << endl;
cout << "Module of b : " << b.module() << endl;
cout << "Module of base of b : " << b.vector::module() << endl;
trivector k;
k = a; // thanks to trivector(vector) definition
// copy of x and y, k.z = 0
vector j;
j = b; // copy of x and y. b.z leaved out
vector *r;
r = &b;
cout << "Surface of r : " << r->surface() << endl;
cout << "Module of r : " << r->module() << endl;
}
class variable can also be CONSTANT
//A class variable can also be CONSTANT. That's just like static,
//except it is allocated a value inside the class declaration and
//that value may not be modified :
#include <iostream.h>
class vector
{
public:
double x;
double y;
const double pi = 3.1415927;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double cilinder_volume ()
{
return x * x / 4 * pi * y;
40 of 56 12.03.99 01:19
C++ Tutorial file:///C'/Eigene Dateien/Manualz/not added/C++ Tutorial for C Users/cppcen.htm
}
};
void main(void)
{
cout << "The value of pi : " << vector::pi << endl << endl;
vector k (3, 4);
cout << "Result : " << k.cilinder_volume() << endl;
}
//A class variable can also be CONSTANT. That's just like static,
//except it is allocated a value inside the class declaration and
//that value may not be modified :
#include <iostream.h>
class vector
{
public:
double x;
double y;
const double pi = 3.1415927;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double cilinder_volume ()
{
return x * x / 4 * pi * y;
40 of 56 12.03.99 01:19
C++ Tutorial file:///C'/Eigene Dateien/Manualz/not added/C++ Tutorial for C Users/cppcen.htm
}
};
void main(void)
{
cout << "The value of pi : " << vector::pi << endl << endl;
vector k (3, 4);
cout << "Result : " << k.cilinder_volume() << endl;
}
class, variable can be declared STATIC
//A class' variable can be declared STATIC. Then only one instance of
//that variable exists, shared by all instances of the class :
#include <iostream.h>
class vector
{
public:
double x;
double y;
static int count;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
count = count + 1;
}
~vector()
{
count = count - 1;
}
};
void main ()
{
vector::count = 0;
cout << "Number of vectors :" << endl;
vector a;
cout << vector::count << endl;
vector b;
cout << vector::count << endl;
vector *r, *u;
r = new vector;
cout << vector::count << endl;
u = new vector;
cout << a.count << endl;
delete (r);
cout << vector::count << endl;
delete (u);
cout << b.count << endl;
}
//A class' variable can be declared STATIC. Then only one instance of
//that variable exists, shared by all instances of the class :
#include <iostream.h>
class vector
{
public:
double x;
double y;
static int count;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
count = count + 1;
}
~vector()
{
count = count - 1;
}
};
void main ()
{
vector::count = 0;
cout << "Number of vectors :" << endl;
vector a;
cout << vector::count << endl;
vector b;
cout << vector::count << endl;
vector *r, *u;
r = new vector;
cout << vector::count << endl;
u = new vector;
cout << a.count << endl;
delete (r);
cout << vector::count << endl;
delete (u);
cout << b.count << endl;
}
OVERLOADING OF ,+, OPERATOR WITH PROTOTYPE SAME AS NAME OF CLASS NAME
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double = 0, double = 0);
vector operator + (vector);
vector operator - (vector);
vector operator - ();
vector operator * (double);
double module();
void set_length (double = 1);
};
vector::vector (double a, double b)
{
x = a;
y = b;
}
vector vector::operator + (vector a)
{
return vector (x + a.x, y + a.y);
}
vector vector::operator - (vector a)
{
return vector (x - a.x, y - a.y);
}
vector vector::operator - ()
{
return vector (-x, -y);
}
vector vector::operator * (double a)
{
return vector (a * x, a * y);
}
double vector::module()
{
return sqrt (x * x + y * y);
}
void vector::set_length (double a)
{
vector &the_vector = *this;
double length = the_vector.module();
x = x / length * a;
y = y / length * a;
}
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}
void main ()
{
vector c (3, 5);
vector *r; // r is a pointer to a vector.
r = new vector; // new allocates the memory necessary
cout << *r << endl; // to hold a vectors' variable,
// calls the constructor who will
// initialize it to 0, 0. Then finally
// new returns the address of the vector.
r->x = 94;
r->y = 345;
cout << *r << endl;
*r = vector (94, 343);
cout << *r << endl;
*r = *r - c;
r->set_length(3);
cout << *r << endl;
*r = (-c * 3 + -*r * 4) * 5;
cout << *r << endl;
delete (r); // Calls the vector destructor then
// frees the memory.
r = &c; // r points towards vector c
cout << *r << endl;
r = new vector (78, 345); // Creates a new vector.
cout << *r << endl; // The constructor will initialise
// the vector's x and y at 78 and 345
cout << "x component of r : " << r->x << endl;
cout << "x component of r : " << (*r).x << endl;
delete (r);
r = new vector[4]; // creates an array of 4 vectors
r[3] = vector (4, 5);
cout << r[3].module() << endl;
delete (r); // deletes the array
int n = 5;
r = new vector[n]; // Cute !
r[1] = vector (432, 3);
cout << r[1] << endl;
delete (r);
}
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double = 0, double = 0);
vector operator + (vector);
vector operator - (vector);
vector operator - ();
vector operator * (double);
double module();
void set_length (double = 1);
};
vector::vector (double a, double b)
{
x = a;
y = b;
}
vector vector::operator + (vector a)
{
return vector (x + a.x, y + a.y);
}
vector vector::operator - (vector a)
{
return vector (x - a.x, y - a.y);
}
vector vector::operator - ()
{
return vector (-x, -y);
}
vector vector::operator * (double a)
{
return vector (a * x, a * y);
}
double vector::module()
{
return sqrt (x * x + y * y);
}
void vector::set_length (double a)
{
vector &the_vector = *this;
double length = the_vector.module();
x = x / length * a;
y = y / length * a;
}
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}
void main ()
{
vector c (3, 5);
vector *r; // r is a pointer to a vector.
r = new vector; // new allocates the memory necessary
cout << *r << endl; // to hold a vectors' variable,
// calls the constructor who will
// initialize it to 0, 0. Then finally
// new returns the address of the vector.
r->x = 94;
r->y = 345;
cout << *r << endl;
*r = vector (94, 343);
cout << *r << endl;
*r = *r - c;
r->set_length(3);
cout << *r << endl;
*r = (-c * 3 + -*r * 4) * 5;
cout << *r << endl;
delete (r); // Calls the vector destructor then
// frees the memory.
r = &c; // r points towards vector c
cout << *r << endl;
r = new vector (78, 345); // Creates a new vector.
cout << *r << endl; // The constructor will initialise
// the vector's x and y at 78 and 345
cout << "x component of r : " << r->x << endl;
cout << "x component of r : " << (*r).x << endl;
delete (r);
r = new vector[4]; // creates an array of 4 vectors
r[3] = vector (4, 5);
cout << r[3].module() << endl;
delete (r); // deletes the array
int n = 5;
r = new vector[n]; // Cute !
r[1] = vector (432, 3);
cout << r[1] << endl;
delete (r);
}
print the equivalent English of a number
# include <ctype.h>
# include <stdio.h>
#include<conio.h>
char *ot[3][9] = {
{ " One", " Two", " Three", " Four", " Five",
" Six", " Seven", " Eight", " Nine" },
{ " Ten", " Twenty", " Thirty", " Forty", " Fifty",
" Sixty", " Seventy", " Eighty", " Ninety" },
{ " Eleven", " Twelve", " Thirteen", " Fourteen",
" Fifteen"," Sixteen"," Seventeen"," Eighteen", " Nineteen"}
};
char *a[5] = { " Hundred", " Thousand", " Lakhs", " Crore", " Arab" } ;
char result[250] = "" ;
char *t[50] ;
main( )
{
int i, j, ind = 0, c, r, pr = -1, e = 0 ;
unsigned long n ;
unsigned long q ;
clrscr( ) ;
printf ( "\nEnter a number : " ) ;
scanf ( "%ld", &n ) ;
printf ( "%ld\n", n ) ;
q = n ;
if ( n == 0 )
strcpy ( result, "Zero" ) ;
else
{
for( i = 0 ; q > 0 ; i++ )
{
if( ( i % 2 ) && i > 2 )
e++ ;
r = q % 10 ;
q /= 10 ;
if ( r != 0 )
{
if ( i == 0 )
t[++ind] = ot[i][r-1];
else if ( i == 1 )
{
if ( r == 1 && pr == 0 )
t[++ind] = ot[i][r-1] ;
else if ( r == 1 && pr > 0 )
t[--ind] = ot[2][r-1] ;
else
t[++ind] = ot[i][r-1] ;
}
else if ( i >= 2 )
{
if ( i == 2 )
{
t[++ind] = a[e] ;
t[++ind] = ot[0][r-1] ;
}
else
{
if ( i % 2 )
{
t[++ind] = a[e] ;
t[++ind] = ot[0][r-1] ;
}
else
{
if ( pr == 0 )
{
t[++ind] = a[e] ;
t[++ind] = ot[1][r-1] ;
}
else if ( r == 1)
t[ind] = ot[2][pr-1] ;
else
t[++ind] = ot[1][r-1] ;
}
}
}
}
pr = r ;
}
}/* End for */
for ( i = ind ; i >= 0 ; i-- )
strcat ( result, t[i] ) ;
printf( "\n%s", result ) ;
getch();
} /* End main */
# include <ctype.h>
# include <stdio.h>
#include<conio.h>
char *ot[3][9] = {
{ " One", " Two", " Three", " Four", " Five",
" Six", " Seven", " Eight", " Nine" },
{ " Ten", " Twenty", " Thirty", " Forty", " Fifty",
" Sixty", " Seventy", " Eighty", " Ninety" },
{ " Eleven", " Twelve", " Thirteen", " Fourteen",
" Fifteen"," Sixteen"," Seventeen"," Eighteen", " Nineteen"}
};
char *a[5] = { " Hundred", " Thousand", " Lakhs", " Crore", " Arab" } ;
char result[250] = "" ;
char *t[50] ;
main( )
{
int i, j, ind = 0, c, r, pr = -1, e = 0 ;
unsigned long n ;
unsigned long q ;
clrscr( ) ;
printf ( "\nEnter a number : " ) ;
scanf ( "%ld", &n ) ;
printf ( "%ld\n", n ) ;
q = n ;
if ( n == 0 )
strcpy ( result, "Zero" ) ;
else
{
for( i = 0 ; q > 0 ; i++ )
{
if( ( i % 2 ) && i > 2 )
e++ ;
r = q % 10 ;
q /= 10 ;
if ( r != 0 )
{
if ( i == 0 )
t[++ind] = ot[i][r-1];
else if ( i == 1 )
{
if ( r == 1 && pr == 0 )
t[++ind] = ot[i][r-1] ;
else if ( r == 1 && pr > 0 )
t[--ind] = ot[2][r-1] ;
else
t[++ind] = ot[i][r-1] ;
}
else if ( i >= 2 )
{
if ( i == 2 )
{
t[++ind] = a[e] ;
t[++ind] = ot[0][r-1] ;
}
else
{
if ( i % 2 )
{
t[++ind] = a[e] ;
t[++ind] = ot[0][r-1] ;
}
else
{
if ( pr == 0 )
{
t[++ind] = a[e] ;
t[++ind] = ot[1][r-1] ;
}
else if ( r == 1)
t[ind] = ot[2][pr-1] ;
else
t[++ind] = ot[1][r-1] ;
}
}
}
}
pr = r ;
}
}/* End for */
for ( i = ind ; i >= 0 ; i-- )
strcat ( result, t[i] ) ;
printf( "\n%s", result ) ;
getch();
} /* End main */
count words and vowels in a line
// program to count number of words in a given string
#include<stdio.h>
#include<conio.h>
void main()
{
int wc,c,i,flag,v,w,space;
wc=c=i=v=w=space=0;
flag=1;
clrscr();
printf("enter a string press enter when you have done\n");
for(i=0 ; (c=getchar()) !='\n' ; i++)
{
if(c==' '''c=='\t')
flag=1;
else if(flag)
{
wc++;
flag=0;
}
if(c=='a'''c=='e' ''c=='i' ''c=='o' ''c=='u')
v++;
if(c!=' '&&c!='\t')
w++;
if(c==' ')
space++;
}
printf("\n\nnumber of words are %d \nno of vovels are %d",wc,v);
printf("\nno of char are %d\nno of space are %d",w,space);
getch();
}
// program to count number of words in a given string
#include<stdio.h>
#include<conio.h>
void main()
{
int wc,c,i,flag,v,w,space;
wc=c=i=v=w=space=0;
flag=1;
clrscr();
printf("enter a string press enter when you have done\n");
for(i=0 ; (c=getchar()) !='\n' ; i++)
{
if(c==' '''c=='\t')
flag=1;
else if(flag)
{
wc++;
flag=0;
}
if(c=='a'''c=='e' ''c=='i' ''c=='o' ''c=='u')
v++;
if(c!=' '&&c!='\t')
w++;
if(c==' ')
space++;
}
printf("\n\nnumber of words are %d \nno of vovels are %d",wc,v);
printf("\nno of char are %d\nno of space are %d",w,space);
getch();
}
analog clock
/*PROGRAM TO CONSTRUCT THE CLOCK*/
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<process.h>
#include<math.h>
#define PI 3.14
#include<stdio.h>
void main()
{
int gd=DETECT,gm;
int h,m,s,xs,ys,xm,ym,xh,yh;
initgraph(&gd,&gm,"c:\\tc\\bgi");
struct time t;
fflush(stdout);
cleardevice();
setfillstyle(6,10);
circle(319,239,239);
circle(319,239,219);
floodfill(556,239,15);
setcolor(9);
settextstyle(1,0,4);
outtextxy(301,37,"12");
outtextxy(480,218," 3");
outtextxy(297,400," 6");
outtextxy(113,218," 9");
gettime(&t);
s=t.ti_sec;
h=t.ti_hour;
m=t.ti_min;
int ang=30;
for(int i=0;i<60;i++)
line(320+210*(cos(PI/180*(90-6*i))),240-210*(sin(PI/180*(90-6*i))),320+200*(cos(PI/180*(90-6*i))),240-200*(sin(PI/180*(90-6*i))));
settextstyle(4,0,3);
outtextxy(263,80,"Neeraj Gulia");
while(1)
{
if (kbhit())
exit(0);
gotoxy(36,25);
printf("%02d::%02d::%02d",h,m,s);
setcolor(4);
xs=320+150*(cos(PI/180*(90-6*s)));
ys=240-150*(sin(PI/180*(90-6*s)));
line(320,240,xs,ys);
setcolor(14);
xm=320+120*(cos(PI/180*(90-6*m)));
ym=240-120*(sin(PI/180*(90-6*m)));
setlinestyle(0,0,3);
line(320,240,xm,ym);
if(s>59)
{
s=0;
m++;
}
setcolor(5);
xh=320+90*(cos(PI/180*(90-ang*h)));
yh=240-90*(sin(PI/180*(90-ang*h)));
line(320,240,xh,yh);
if(m>59)
{
m=0;
h++;
s=0;
}
delay(980);
sound(40);
delay(50);
nosound();
setcolor(0);
line(320,240,xh,yh);
line(320,240,xm,ym);
setlinestyle(0,0,0);
line(320,240,xs,ys);
s++;
}
}
/*PROGRAM TO CONSTRUCT THE CLOCK*/
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<process.h>
#include<math.h>
#define PI 3.14
#include<stdio.h>
void main()
{
int gd=DETECT,gm;
int h,m,s,xs,ys,xm,ym,xh,yh;
initgraph(&gd,&gm,"c:\\tc\\bgi");
struct time t;
fflush(stdout);
cleardevice();
setfillstyle(6,10);
circle(319,239,239);
circle(319,239,219);
floodfill(556,239,15);
setcolor(9);
settextstyle(1,0,4);
outtextxy(301,37,"12");
outtextxy(480,218," 3");
outtextxy(297,400," 6");
outtextxy(113,218," 9");
gettime(&t);
s=t.ti_sec;
h=t.ti_hour;
m=t.ti_min;
int ang=30;
for(int i=0;i<60;i++)
line(320+210*(cos(PI/180*(90-6*i))),240-210*(sin(PI/180*(90-6*i))),320+200*(cos(PI/180*(90-6*i))),240-200*(sin(PI/180*(90-6*i))));
settextstyle(4,0,3);
outtextxy(263,80,"Neeraj Gulia");
while(1)
{
if (kbhit())
exit(0);
gotoxy(36,25);
printf("%02d::%02d::%02d",h,m,s);
setcolor(4);
xs=320+150*(cos(PI/180*(90-6*s)));
ys=240-150*(sin(PI/180*(90-6*s)));
line(320,240,xs,ys);
setcolor(14);
xm=320+120*(cos(PI/180*(90-6*m)));
ym=240-120*(sin(PI/180*(90-6*m)));
setlinestyle(0,0,3);
line(320,240,xm,ym);
if(s>59)
{
s=0;
m++;
}
setcolor(5);
xh=320+90*(cos(PI/180*(90-ang*h)));
yh=240-90*(sin(PI/180*(90-ang*h)));
line(320,240,xh,yh);
if(m>59)
{
m=0;
h++;
s=0;
}
delay(980);
sound(40);
delay(50);
nosound();
setcolor(0);
line(320,240,xh,yh);
line(320,240,xm,ym);
setlinestyle(0,0,0);
line(320,240,xs,ys);
s++;
}
}
adding 2 numbers
void main()
{
int a=10;
int b=20;
int c;
c=a+b;
printf(" the value will b ",c);
getch();
}
void main()
{
int a=10;
int b=20;
int c;
c=a+b;
printf(" the value will b ",c);
getch();
}
write inside a character array
//Here is a program that writes inside a character array :
#include <iostream.h>
#include <strstrea.h>
#include <string.h>
#include <math.h>
void main ()
{
char a[1024];
ostrstream b(a, 1024);
b.seekp(0); // Start from first char.
b << "2 + 2 = " << 2 + 2 << ends; // ( ends, not endl )
// ends is simply the
// null character '\0'
cout << a << endl;
double v = 2;
strcpy (a, "A sinus : ");
b.seekp(strlen (a));
b << "sin (" << v << ") = " << sin(v) << ends;
cout << a << endl;
}
//Here is a program that writes inside a character array :
#include <iostream.h>
#include <strstrea.h>
#include <string.h>
#include <math.h>
void main ()
{
char a[1024];
ostrstream b(a, 1024);
b.seekp(0); // Start from first char.
b << "2 + 2 = " << 2 + 2 << ends; // ( ends, not endl )
// ends is simply the
// null character '\0'
cout << a << endl;
double v = 2;
strcpy (a, "A sinus : ");
b.seekp(strlen (a));
b << "sin (" << v << ") = " << sin(v) << ends;
cout << a << endl;
}
programme for sorted linked list...(not only linked list MARK sorted.)
#include<iostream.h>
#include<process.h>
class link
{
link* next;
int data,no;
public :
link* sort(link*);
void traverse(link*);
//link* dele (link*);
};
link * link::sort(link* temp)
{
link* newlink;
link* dummy1;
newlink=new link;
cout<<"\nEnter Data (only positive number) :";
cin>>no;
dummy1 = temp;
if (temp==NULL '' dummy1->data > no)
{
newlink->data = no;
newlink->next=temp;
temp=newlink;
return temp;
}
else
{
link *cur;
link *dummy;
cur=temp;
dummy = cur->next ;
while(cur->next!=NULL)
{
if(dummy->data > no)
{
newlink->next = cur->next;
newlink->data = no;
cur->next = newlink;
return temp;
}
dummy=dummy->next ;
cur=cur->next;
}
newlink->data = no;
newlink->next=NULL;
cur->next=newlink;
}
return temp;
}
void link::traverse(link *temp)
{
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
void main()
{
link *first=NULL,l1;
int choice;
while(1)
{
cout<<"\n*************** SORTED LINK LIST (For Integer Only) ***************\n\n";
cout<<"Choices Are :-\n=> [1] For Insert \n=> [2] For Traverse \n=> [3] For Exit";
cout<<"\n\nEnter Your choice : ";
cin>>choice;
switch (choice)
{
case 1:
first=l1.sort(first);
break;
case 2:
l1.traverse(first);
break;
case 3:
exit(0);
}
}
}
#include<iostream.h>
#include<process.h>
class link
{
link* next;
int data,no;
public :
link* sort(link*);
void traverse(link*);
//link* dele (link*);
};
link * link::sort(link* temp)
{
link* newlink;
link* dummy1;
newlink=new link;
cout<<"\nEnter Data (only positive number) :";
cin>>no;
dummy1 = temp;
if (temp==NULL '' dummy1->data > no)
{
newlink->data = no;
newlink->next=temp;
temp=newlink;
return temp;
}
else
{
link *cur;
link *dummy;
cur=temp;
dummy = cur->next ;
while(cur->next!=NULL)
{
if(dummy->data > no)
{
newlink->next = cur->next;
newlink->data = no;
cur->next = newlink;
return temp;
}
dummy=dummy->next ;
cur=cur->next;
}
newlink->data = no;
newlink->next=NULL;
cur->next=newlink;
}
return temp;
}
void link::traverse(link *temp)
{
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
void main()
{
link *first=NULL,l1;
int choice;
while(1)
{
cout<<"\n*************** SORTED LINK LIST (For Integer Only) ***************\n\n";
cout<<"Choices Are :-\n=> [1] For Insert \n=> [2] For Traverse \n=> [3] For Exit";
cout<<"\n\nEnter Your choice : ";
cin>>choice;
switch (choice)
{
case 1:
first=l1.sort(first);
break;
case 2:
l1.traverse(first);
break;
case 3:
exit(0);
}
}
}
programme to draw a interesting picture using line() function
/* draw a interesting picture using line() */
/* ================================================== */
#include <graphics.h>
#include <math.h>
#include <conio.h>
void main(void)
{
int driver = DETECT,mode;
int x[10],y[10];
int x_center = 360, y_center = 180, rad = 100;
int i,j;
initgraph(&driver,&mode,"c:\\tc\\bgi");
for ( i = 0; i < 10; i++ )
{
x[i] = x_center + rad * cos(36*i*3.14159/180);
y[i] = y_center + rad * sin(36*i*3.14159/180);
}
for ( i = 0; i < 10; i++ )
for ( j = 0; j < 10; j++ )
line(x[i],y[i],x[j],y[j]);
getch(); /* press any key return to TEXT mode */
closegraph();
}
/* draw a interesting picture using line() */
/* ================================================== */
#include <graphics.h>
#include <math.h>
#include <conio.h>
void main(void)
{
int driver = DETECT,mode;
int x[10],y[10];
int x_center = 360, y_center = 180, rad = 100;
int i,j;
initgraph(&driver,&mode,"c:\\tc\\bgi");
for ( i = 0; i < 10; i++ )
{
x[i] = x_center + rad * cos(36*i*3.14159/180);
y[i] = y_center + rad * sin(36*i*3.14159/180);
}
for ( i = 0; i < 10; i++ )
for ( j = 0; j < 10; j++ )
line(x[i],y[i],x[j],y[j]);
getch(); /* press any key return to TEXT mode */
closegraph();
}
a programme for getpixel() application
/* getpixel() application. */
/* ================================================== */
#include<graphics.h>
#include<conio.h>
void main()
{
int driver = DETECT,mode;
int i;
initgraph(&driver,&mode,"c:\\borlandc\\bgi");
line(100,100,500,100);
for ( i = 20; i < 300; i++ )
if ( getpixel(300,i) == WHITE )
{
setcolor(BLUE);
circle(300,i,5);
}
else
putpixel(300,i,WHITE);
getch();
closegraph();
}
/* getpixel() application. */
/* ================================================== */
#include<graphics.h>
#include<conio.h>
void main()
{
int driver = DETECT,mode;
int i;
initgraph(&driver,&mode,"c:\\borlandc\\bgi");
line(100,100,500,100);
for ( i = 20; i < 300; i++ )
if ( getpixel(300,i) == WHITE )
{
setcolor(BLUE);
circle(300,i,5);
}
else
putpixel(300,i,WHITE);
getch();
closegraph();
}
copy a file partly.(only required portion).more USEFUL for AUDIO or VEDIO files
/*filecopy.c : can copy files partly*/
#include <stdio.h>
#include <stdlib.h>
int file_copy(char *oldname, char *newname, long bytes1, long bytes2);
long get_bytes(float percent, char *source);
main()
{
char source[80], destination[80];
float percent1, percent2;
/*Get the file names*/
puts("Enter source file:");
printf("\t");
gets(source);
puts("\nEnter destination file \(WARNING: If the file exists, it will be OVERWRITTEN\): ");
printf("\t");
gets(destination);
/*Get the positions in percentage*/
puts("\nEnter start percentage (recommended: 0): ");
printf("\t");
scanf("%f", &percent1);
do
{
puts("\nEnter end percentage:");
printf("\t");
scanf("%f", &percent2);
} while ( percent2 < percent1 );
if ( file_copy( source, destination, get_bytes(percent1, source), get_bytes(percent2, source) ) == 1 )
puts("\nCopy operation SUCCESSFUL");
else
fprintf(stderr, "\nError during copy operation");
fflush(stdin);
puts("\nPress any key to exit . . . ");
getchar();
return(0);
}
/*Function for actual copying of file, return 1 on success, 0 otherwise*/
int file_copy( char *oldname, char *newname, long bytes1, long bytes2)
/*bytes1 denotes the start position in bytes, bytes2 denotes the end position*/
{
FILE *fold, *fnew;
int c;
if ( ( fold = fopen( oldname, "rb" ) ) == NULL )
return 0;
if ( ( fnew = fopen( newname, "wb" ) ) == NULL )
{
fclose ( fold );
return 0;
}
/*Set file pointer to proper start location, as specified by user*/
if ( ( fseek(fold, bytes1, SEEK_SET) != 0 ) )
{
fprintf(stderr, "\nError using fseek().");
exit(1);
}
while (1)
{
c=fgetc(fold);
/*Continue copying until end of file or until the requested limit has been reached*/
if ( !feof( fold ) && ftell(fold) <= bytes2)
fputc( c, fnew );
else
break;
}
fclose ( fnew );
fclose ( fold );
return 1;
}
/*This function finds how many bytes need to copied, calculating it from the percentage inputted by the user*/
long get_bytes(float percent, char *source)
{
long bytes;
FILE *fold;
if (percent<=100)
{
if ( ( fold = fopen( source, "rb" ) ) == NULL )
{
puts("Error opening source file");
exit(1);
}
if ( (fseek(fold, 0, SEEK_END))!=0)
{
fprintf(stderr, "\nError using fseek().");
exit(1);
}
bytes=ftell(fold);
bytes*=(percent/100);
}
else
{
fprintf(stderr, "Error in input");
exit(1);
}
fclose(fold);
return bytes;
}
/*filecopy.c : can copy files partly*/
#include <stdio.h>
#include <stdlib.h>
int file_copy(char *oldname, char *newname, long bytes1, long bytes2);
long get_bytes(float percent, char *source);
main()
{
char source[80], destination[80];
float percent1, percent2;
/*Get the file names*/
puts("Enter source file:");
printf("\t");
gets(source);
puts("\nEnter destination file \(WARNING: If the file exists, it will be OVERWRITTEN\): ");
printf("\t");
gets(destination);
/*Get the positions in percentage*/
puts("\nEnter start percentage (recommended: 0): ");
printf("\t");
scanf("%f", &percent1);
do
{
puts("\nEnter end percentage:");
printf("\t");
scanf("%f", &percent2);
} while ( percent2 < percent1 );
if ( file_copy( source, destination, get_bytes(percent1, source), get_bytes(percent2, source) ) == 1 )
puts("\nCopy operation SUCCESSFUL");
else
fprintf(stderr, "\nError during copy operation");
fflush(stdin);
puts("\nPress any key to exit . . . ");
getchar();
return(0);
}
/*Function for actual copying of file, return 1 on success, 0 otherwise*/
int file_copy( char *oldname, char *newname, long bytes1, long bytes2)
/*bytes1 denotes the start position in bytes, bytes2 denotes the end position*/
{
FILE *fold, *fnew;
int c;
if ( ( fold = fopen( oldname, "rb" ) ) == NULL )
return 0;
if ( ( fnew = fopen( newname, "wb" ) ) == NULL )
{
fclose ( fold );
return 0;
}
/*Set file pointer to proper start location, as specified by user*/
if ( ( fseek(fold, bytes1, SEEK_SET) != 0 ) )
{
fprintf(stderr, "\nError using fseek().");
exit(1);
}
while (1)
{
c=fgetc(fold);
/*Continue copying until end of file or until the requested limit has been reached*/
if ( !feof( fold ) && ftell(fold) <= bytes2)
fputc( c, fnew );
else
break;
}
fclose ( fnew );
fclose ( fold );
return 1;
}
/*This function finds how many bytes need to copied, calculating it from the percentage inputted by the user*/
long get_bytes(float percent, char *source)
{
long bytes;
FILE *fold;
if (percent<=100)
{
if ( ( fold = fopen( source, "rb" ) ) == NULL )
{
puts("Error opening source file");
exit(1);
}
if ( (fseek(fold, 0, SEEK_END))!=0)
{
fprintf(stderr, "\nError using fseek().");
exit(1);
}
bytes=ftell(fold);
bytes*=(percent/100);
}
else
{
fprintf(stderr, "Error in input");
exit(1);
}
fclose(fold);
return bytes;
}
programme to show the include files of a specified .cpp or .h file
//to show the include files of a specified .cpp or .h file...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *file;
char filename[_MAX_PATH];
void main()
{
re_open:
system("cls");
puts("Type in the name of the .cpp or .h file whose #include files are to be read:");
gets(filename);
system("cls");
file = fopen(filename, "r");
if(!file)
{
printf("The file '%s' could not be opened.\n", filename);
system("pause");
goto re_open;
}
else
{
int icount = 0;
do
{
char line[256];
fgets(line, 256, file);
if(!strncmp(line, "#include", 8))
{
char *result;
result = strpbrk(line, "<\"");
result ++;
result[strlen(result) - 2] = ' ';
printf(result);
icount ++;
}
}while(!feof(file));
if(icount == 0)
{
puts("No #include files");
}
system("pause");
fclose(file);
goto re_open;
}
}
//to show the include files of a specified .cpp or .h file...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *file;
char filename[_MAX_PATH];
void main()
{
re_open:
system("cls");
puts("Type in the name of the .cpp or .h file whose #include files are to be read:");
gets(filename);
system("cls");
file = fopen(filename, "r");
if(!file)
{
printf("The file '%s' could not be opened.\n", filename);
system("pause");
goto re_open;
}
else
{
int icount = 0;
do
{
char line[256];
fgets(line, 256, file);
if(!strncmp(line, "#include", 8))
{
char *result;
result = strpbrk(line, "<\"");
result ++;
result[strlen(result) - 2] = ' ';
printf(result);
icount ++;
}
}while(!feof(file));
if(icount == 0)
{
puts("No #include files");
}
system("pause");
fclose(file);
goto re_open;
}
}
menu selection like in windows
// program to control a line of sign
// control the cursor
//
#include<conio.h>
#include<stdio.h>
#include<process.h>
void main()
{
char ch,
*menu[]={"first ","second","third ","fourth","fifth "},
*first[]={"one","0001"},
*second[]={"two","0002"},
*third[]={"three","0003"},
*fourth[]={"four","0004"};
int i,cur=0;
clrscr();
textcolor(3);
for(i=0;i<=4;i++)
{
gotoxy(8+13*i,3);
cprintf("%s",menu[i]);
}
_setcursortype(0);
while(1)
{
ch=getch();
switch(ch)
{
case 77:
textcolor(3);
textbackground(0);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
if(cur==4)
cur=0;
else
cur++;
textcolor(0);
textbackground(3);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
break;
case 75:
textcolor(3);
textbackground(0);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
if(cur==0)
cur=4;
else
cur--;
textcolor(0);
textbackground(3);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
break;
case 72:
break;
case 27:
exit(1);
}
}
}
// program to control a line of sign
// control the cursor
//
#include<conio.h>
#include<stdio.h>
#include<process.h>
void main()
{
char ch,
*menu[]={"first ","second","third ","fourth","fifth "},
*first[]={"one","0001"},
*second[]={"two","0002"},
*third[]={"three","0003"},
*fourth[]={"four","0004"};
int i,cur=0;
clrscr();
textcolor(3);
for(i=0;i<=4;i++)
{
gotoxy(8+13*i,3);
cprintf("%s",menu[i]);
}
_setcursortype(0);
while(1)
{
ch=getch();
switch(ch)
{
case 77:
textcolor(3);
textbackground(0);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
if(cur==4)
cur=0;
else
cur++;
textcolor(0);
textbackground(3);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
break;
case 75:
textcolor(3);
textbackground(0);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
if(cur==0)
cur=4;
else
cur--;
textcolor(0);
textbackground(3);
gotoxy(8+13*cur,3);
cprintf("%s",menu[cur]);
break;
case 72:
break;
case 27:
exit(1);
}
}
}
shell sort
#include<iostream.h>
#include<conio.h>
void main()
{
int k,i,temp,n,a[20],swap,gap;
clrscr();
cout<<"enter the no. of elements: ";
cin>>n;
cout<<"enter elements: \n";
for(i=1;i<=n;i++)
cin>>a[i];
gap=n/2;
k=0;
do{
do{
swap=0;
k++;
for(i=1;i<=n-gap;i++)
if(a[i]>a[i+gap])
{
temp=a[i];
a[i]=a[i+gap];
a[i+gap]=temp;
swap=1;
}
}while(swap);
gap=gap/2;
}while(gap);
cout<<"sorted list is: \n";
for(i=1;i<=n;i++)
cout<<a[i]<<endl;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int k,i,temp,n,a[20],swap,gap;
clrscr();
cout<<"enter the no. of elements: ";
cin>>n;
cout<<"enter elements: \n";
for(i=1;i<=n;i++)
cin>>a[i];
gap=n/2;
k=0;
do{
do{
swap=0;
k++;
for(i=1;i<=n-gap;i++)
if(a[i]>a[i+gap])
{
temp=a[i];
a[i]=a[i+gap];
a[i+gap]=temp;
swap=1;
}
}while(swap);
gap=gap/2;
}while(gap);
cout<<"sorted list is: \n";
for(i=1;i<=n;i++)
cout<<a[i]<<endl;
getch();
}
quick sort
#include<iostream.h>
#include<conio.h>
int loc=0;
void main()
{
int i,n,a[20],lower[20],upper[20],top,beg,end;
void quick(int *,int,int,int,int);
clrscr();
cout<<"enter the no. of elements : ";
cin>>n;
cout<<"enter elements: \n";
for(i=1;i<=n;i++)
cin>>a[i];
top=0;
if(n>1)
{
top=top+1;
lower[1]=1;
upper[1]=n;
}
while(top!=0)
{
beg=lower[top];
end=upper[top];
top--;
quick(a,n,beg,end,loc);
if(beg<loc-1)
{
top++;
lower[top]=beg;
upper[top]=loc-1;
}
if(loc+1<end)
{
top++;
lower[top]=loc+1;
upper[top]=end;
}
}
cout<<"sorted list is: \n";
for(i=1;i<=n;i++)
cout<<a[i]<<endl;
}
void quick(int a[],int n,int beg, int end, int loc)
{
int left,right,temp;
left=beg;
right=end;
loc=beg;
a:
while((a[loc]<=a[right]) && (loc!=right))
right=right-1;
if (loc==right)
return;
if(a[loc]>a[right])
{
temp=a[loc];
a[loc]=a[right];
a[right]=temp;
loc=right;
}
while((a[left]<=a[loc]) && (left!=loc))
left=left+1;
if(loc==left)
return;
if(a[left]>a[loc])
{
temp=a[left];
a[left]=a[loc];
a[loc]=temp;
loc=left;
goto a;
}
}
#include<iostream.h>
#include<conio.h>
int loc=0;
void main()
{
int i,n,a[20],lower[20],upper[20],top,beg,end;
void quick(int *,int,int,int,int);
clrscr();
cout<<"enter the no. of elements : ";
cin>>n;
cout<<"enter elements: \n";
for(i=1;i<=n;i++)
cin>>a[i];
top=0;
if(n>1)
{
top=top+1;
lower[1]=1;
upper[1]=n;
}
while(top!=0)
{
beg=lower[top];
end=upper[top];
top--;
quick(a,n,beg,end,loc);
if(beg<loc-1)
{
top++;
lower[top]=beg;
upper[top]=loc-1;
}
if(loc+1<end)
{
top++;
lower[top]=loc+1;
upper[top]=end;
}
}
cout<<"sorted list is: \n";
for(i=1;i<=n;i++)
cout<<a[i]<<endl;
}
void quick(int a[],int n,int beg, int end, int loc)
{
int left,right,temp;
left=beg;
right=end;
loc=beg;
a:
while((a[loc]<=a[right]) && (loc!=right))
right=right-1;
if (loc==right)
return;
if(a[loc]>a[right])
{
temp=a[loc];
a[loc]=a[right];
a[right]=temp;
loc=right;
}
while((a[left]<=a[loc]) && (left!=loc))
left=left+1;
if(loc==left)
return;
if(a[left]>a[loc])
{
temp=a[left];
a[left]=a[loc];
a[loc]=temp;
loc=left;
goto a;
}
}
animation
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<alloc.h>
#include<dos.h>
void main()
{
clrscr();
int driver=DETECT,mode,maxx,maxy,area,ch,x=25,y=30,xdir=1,ydir=-1;
char *buff;
initgraph(&driver,&mode,"\\tc\\bgi");
setcolor(WHITE);
setfillstyle(SOLID_FILL,RED);
circle(50,50,25);
floodfill(50,50,WHITE);
area=imagesize(25,25,75,75);
buff=(char *)malloc(area);
getimage(25,25,75,75,buff);
maxx=getmaxx();
maxy=getmaxy();
while (1)
{
if (kbhit())
break;
putimage(x,y,buff,XOR_PUT);
x=x+(xdir*5);
y=y+(ydir*3);
cleardevice();
putimage(x,y,buff,XOR_PUT);
if (x> maxx-50 '' x<0)
{
xdir*=-1;
}
if (y>maxy-60 '' y<20)
{
ydir*=-1;
}
delay(20);
}
getch();
closegraph();
}
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<alloc.h>
#include<dos.h>
void main()
{
clrscr();
int driver=DETECT,mode,maxx,maxy,area,ch,x=25,y=30,xdir=1,ydir=-1;
char *buff;
initgraph(&driver,&mode,"\\tc\\bgi");
setcolor(WHITE);
setfillstyle(SOLID_FILL,RED);
circle(50,50,25);
floodfill(50,50,WHITE);
area=imagesize(25,25,75,75);
buff=(char *)malloc(area);
getimage(25,25,75,75,buff);
maxx=getmaxx();
maxy=getmaxy();
while (1)
{
if (kbhit())
break;
putimage(x,y,buff,XOR_PUT);
x=x+(xdir*5);
y=y+(ydir*3);
cleardevice();
putimage(x,y,buff,XOR_PUT);
if (x> maxx-50 '' x<0)
{
xdir*=-1;
}
if (y>maxy-60 '' y<20)
{
ydir*=-1;
}
delay(20);
}
getch();
closegraph();
}
#include<stdio.h>
#include<conio.h>
#include<dos.h>
main()
{
clrscr();
outportb(0x64,0xAD); /*Code for disabling the KEYBOARD*/
printf("
Keyboard Disabled");
delay(10000);
clrscr();
printf("
Keyboard Enabled");
outportb(0x64,0xAE); /*Code for enabling the KEYBOARD*/
getch();
}
#include<conio.h>
#include<dos.h>
main()
{
clrscr();
outportb(0x64,0xAD); /*Code for disabling the KEYBOARD*/
printf("
Keyboard Disabled");
delay(10000);
clrscr();
printf("
Keyboard Enabled");
outportb(0x64,0xAE); /*Code for enabling the KEYBOARD*/
getch();
}
to print like in calculator, i.e. from right to left
//program to enter the name of the user
#include<conio.h>
#include<stdio.h>
#define row 41
#define col 2
void main()
{
char *name;
int i;
clrscr();
printf("enter your name: "); // 18
for(i=0;;i++)
{
gotoxy(row,col);
name[i]=getch();
if(name[i]=='\r')
break;
gotoxy(row-i,col);
printf("%s",name);
}
}
//program to enter the name of the user
#include<conio.h>
#include<stdio.h>
#define row 41
#define col 2
void main()
{
char *name;
int i;
clrscr();
printf("enter your name: "); // 18
for(i=0;;i++)
{
gotoxy(row,col);
name[i]=getch();
if(name[i]=='\r')
break;
gotoxy(row-i,col);
printf("%s",name);
}
}
star simmulation
#include<dos.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#include"apvector.h"
#define LEFT 75
#define RIGHT 77
typedef unsigned char byte;
void set_mode(byte mode)
{
union REGS regs;
regs.h.ah = 0x00;
regs.h.al = mode;
int86(0x10, ®s, ®s);
}
void pixel(int x,int y,byte color)
{
union REGS regs;
regs.h.ah = 0x0C;
regs.h.al = color;
regs.x.cx = x;
regs.x.dx = y;
int86(0x10, ®s, ®s);
}
void opening(void)
{
clrscr();
_setcursortype(_NOCURSOR);
gotoxy(30,1); cout<<"Starfield Simulation";
gotoxy(37,2); cout<<"by Sean Bugel";
gotoxy(2,19); cout<<"+ to speed up star field";
gotoxy(2,20); cout<<"- to slow down star field";
gotoxy(2,21); printf("%c to move the star field right",16);
gotoxy(2,22); printf("%c to move the star field left",17);
gotoxy(2,23); cout<<"'Esc' to quit simulation";
while(!kbhit())
{
gotoxy(1,25);
clreol();
delay(750);
gotoxy(28,25);
cout<<"Press any key to continue...";
delay(1000);
}
clrscr();
}
void main(void)
{
opening();
set_mode(0x13);
randomize();
apvector<int>x(31); //array of x axis for 30 stars
apvector<int>y(31); //array of y axis for 30 stars
int i=8,finish=0,a=0,b=0,inc=2,c,dir=0; //i is star speed, finish is variable for exit from loop
//a & b used for finding random star position loop
//inc slows down second and third field
//dir is variable to choose direction of starfield, 0 left, 1 right
while(a!=30) //allocate 30 x positions
{
x[a]=rand()%320;
a++;
}
while(b!=30) //allocate 30 y positions
{
y[b]=rand()%320;
b++;
}
c=1;
while(c!=10) //place 10 WHITE stars
{
pixel(x[c],y[c],WHITE);
c++;
}
while(!finish)
{
if(kbhit())
{
switch(getch()) //This code is for controlling the speed
{
case 61: //+
{
if(i>=2){i--;}
else break;
} break;
case 43: //+
{
if(i>=2){i--;}
else break;
} break;
case 95: //-
{
if(i<=16){i++;}
else break;
} break;
case 45: //-
{
if(i<=16){i++;}
else break;
} break;
case LEFT:
{
dir=0;
} break;
case RIGHT:
{
dir=1;
} break;
case 27: //Quit
{
finish=1;
} break;
default: break;
}
}
inc++; //variable used to slow down second and third field
c=1;
while(c<=10) //erase first field
{
pixel(x[c],y[c],BLACK);
c++;
}
c=1;
while(c<=10) //checks to see if field 1 stars hit border
{
if(dir==0) //if direction is left
{
if(x[c]!=1){x[c]--;} else{y[c]=rand()%200;x[c]=320;}
}
else if(dir=1) //if direction is right
{
if(x[c]!=320){x[c]++;} else{y[c]=rand()%200;x[c]=1;}
}
c++;
}
if(inc%2==0) //second star field algos
{
c=11;
while(c<=20) //erase second field
{
pixel(x[c],y[c],BLACK);
c++;
}
c=11;
while(c<=20) //checks to see if field 2 stars hit border
{
if(dir==0) //if direction is left
{
if(x[c]!=1){x[c]--;} else{y[c]=rand()%200;x[c]=320;}
}
else if(dir=1) //if direction is right
{
if(x[c]!=320){x[c]++;} else{y[c]=rand()%200;x[c]=1;}
}
c++;
}
c=11;
while(c<=20) //place 10 LIGHTGRAY stars
{
pixel(x[c],y[c],LIGHTGRAY);
c++;
}
} //end of second star field data
if( inc%5==0) //third star field algos
{
c=21;
while(c<=30) //erase third field
{
pixel(x[c],y[c],BLACK);
c++;
}
c=21;
while(c<=30) //checks to see if field 3 stars hit border
{
if(dir==0) //if direction is left
{
if(x[c]!=1){x[c]--;} else{y[c]=rand()%200;x[c]=320;}
}
else if(dir=1) //if direction is right
{
if(x[c]!=320){x[c]++;} else{y[c]=rand()%200;x[c]=1;}
}
c++;
}
c=21;
while(c<=30) //place 10 dark gray stars
{
pixel(x[c],y[c],DARKGRAY);
c++;
}
} //end of third star field data
c=1;
while(c<=10) //place 10 white stars
{
pixel(x[c],y[c],WHITE);
c++;
}
delay(i);
if(inc==500){inc=2;} //to keep the variable from getting too big
}
set_mode(0x03);
_setcursortype(_NORMALCURSOR);
}
#include<dos.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#include"apvector.h"
#define LEFT 75
#define RIGHT 77
typedef unsigned char byte;
void set_mode(byte mode)
{
union REGS regs;
regs.h.ah = 0x00;
regs.h.al = mode;
int86(0x10, ®s, ®s);
}
void pixel(int x,int y,byte color)
{
union REGS regs;
regs.h.ah = 0x0C;
regs.h.al = color;
regs.x.cx = x;
regs.x.dx = y;
int86(0x10, ®s, ®s);
}
void opening(void)
{
clrscr();
_setcursortype(_NOCURSOR);
gotoxy(30,1); cout<<"Starfield Simulation";
gotoxy(37,2); cout<<"by Sean Bugel";
gotoxy(2,19); cout<<"+ to speed up star field";
gotoxy(2,20); cout<<"- to slow down star field";
gotoxy(2,21); printf("%c to move the star field right",16);
gotoxy(2,22); printf("%c to move the star field left",17);
gotoxy(2,23); cout<<"'Esc' to quit simulation";
while(!kbhit())
{
gotoxy(1,25);
clreol();
delay(750);
gotoxy(28,25);
cout<<"Press any key to continue...";
delay(1000);
}
clrscr();
}
void main(void)
{
opening();
set_mode(0x13);
randomize();
apvector<int>x(31); //array of x axis for 30 stars
apvector<int>y(31); //array of y axis for 30 stars
int i=8,finish=0,a=0,b=0,inc=2,c,dir=0; //i is star speed, finish is variable for exit from loop
//a & b used for finding random star position loop
//inc slows down second and third field
//dir is variable to choose direction of starfield, 0 left, 1 right
while(a!=30) //allocate 30 x positions
{
x[a]=rand()%320;
a++;
}
while(b!=30) //allocate 30 y positions
{
y[b]=rand()%320;
b++;
}
c=1;
while(c!=10) //place 10 WHITE stars
{
pixel(x[c],y[c],WHITE);
c++;
}
while(!finish)
{
if(kbhit())
{
switch(getch()) //This code is for controlling the speed
{
case 61: //+
{
if(i>=2){i--;}
else break;
} break;
case 43: //+
{
if(i>=2){i--;}
else break;
} break;
case 95: //-
{
if(i<=16){i++;}
else break;
} break;
case 45: //-
{
if(i<=16){i++;}
else break;
} break;
case LEFT:
{
dir=0;
} break;
case RIGHT:
{
dir=1;
} break;
case 27: //Quit
{
finish=1;
} break;
default: break;
}
}
inc++; //variable used to slow down second and third field
c=1;
while(c<=10) //erase first field
{
pixel(x[c],y[c],BLACK);
c++;
}
c=1;
while(c<=10) //checks to see if field 1 stars hit border
{
if(dir==0) //if direction is left
{
if(x[c]!=1){x[c]--;} else{y[c]=rand()%200;x[c]=320;}
}
else if(dir=1) //if direction is right
{
if(x[c]!=320){x[c]++;} else{y[c]=rand()%200;x[c]=1;}
}
c++;
}
if(inc%2==0) //second star field algos
{
c=11;
while(c<=20) //erase second field
{
pixel(x[c],y[c],BLACK);
c++;
}
c=11;
while(c<=20) //checks to see if field 2 stars hit border
{
if(dir==0) //if direction is left
{
if(x[c]!=1){x[c]--;} else{y[c]=rand()%200;x[c]=320;}
}
else if(dir=1) //if direction is right
{
if(x[c]!=320){x[c]++;} else{y[c]=rand()%200;x[c]=1;}
}
c++;
}
c=11;
while(c<=20) //place 10 LIGHTGRAY stars
{
pixel(x[c],y[c],LIGHTGRAY);
c++;
}
} //end of second star field data
if( inc%5==0) //third star field algos
{
c=21;
while(c<=30) //erase third field
{
pixel(x[c],y[c],BLACK);
c++;
}
c=21;
while(c<=30) //checks to see if field 3 stars hit border
{
if(dir==0) //if direction is left
{
if(x[c]!=1){x[c]--;} else{y[c]=rand()%200;x[c]=320;}
}
else if(dir=1) //if direction is right
{
if(x[c]!=320){x[c]++;} else{y[c]=rand()%200;x[c]=1;}
}
c++;
}
c=21;
while(c<=30) //place 10 dark gray stars
{
pixel(x[c],y[c],DARKGRAY);
c++;
}
} //end of third star field data
c=1;
while(c<=10) //place 10 white stars
{
pixel(x[c],y[c],WHITE);
c++;
}
delay(i);
if(inc==500){inc=2;} //to keep the variable from getting too big
}
set_mode(0x03);
_setcursortype(_NORMALCURSOR);
}
change color of the screen characters
#include<stdio.h>#include<dos.h>
#include<stdlib.h>
int main(void)
{
char far *vm=0xB8000000;
int i,j,temp,tm,k;
char *ch="the quick brown fox jumps over the little lazy dog. ";
_setcursortype(0);
clrscr();
gotoxy(8,2);
printf("hello my dear friends my this program will change the color \n\t\t of all the characters as you can see\n\n");
// gotoxy(6,6);
for(i=0;i<17;i++)
printf("%s",ch);
gotoxy(7,18);
printf("so you are enjoying the dancing of colors of all the characters");
temp=3;
while(!kbhit())
{
if(temp==15)
temp=3;
temp++;
tm=random(255);
for(i=0,j=0,k=1;i<4000;i+=2)
{
if(j>temp)
j=1;
else j++;
if( isalpha (* (vm+i) ))
*(vm+i+1)=j;
if(i>3039)
{
if(k>tm)
k=1;
else
k+=4;
*(vm+i+1)=k;
}
}
delay(150);
}
return 0;
}
#include<stdio.h>#include<dos.h>
#include<stdlib.h>
int main(void)
{
char far *vm=0xB8000000;
int i,j,temp,tm,k;
char *ch="the quick brown fox jumps over the little lazy dog. ";
_setcursortype(0);
clrscr();
gotoxy(8,2);
printf("hello my dear friends my this program will change the color \n\t\t of all the characters as you can see\n\n");
// gotoxy(6,6);
for(i=0;i<17;i++)
printf("%s",ch);
gotoxy(7,18);
printf("so you are enjoying the dancing of colors of all the characters");
temp=3;
while(!kbhit())
{
if(temp==15)
temp=3;
temp++;
tm=random(255);
for(i=0,j=0,k=1;i<4000;i+=2)
{
if(j>temp)
j=1;
else j++;
if( isalpha (* (vm+i) ))
*(vm+i+1)=j;
if(i>3039)
{
if(k>tm)
k=1;
else
k+=4;
*(vm+i+1)=k;
}
}
delay(150);
}
return 0;
}
#include<stdio.h>#include<dos.h>
#include<stdlib.h>
int main(void)
{
char far *vm=0xB8000000;
int i,j,temp;
_setcursortype(0);
gotoxy(17,24);
clrscr();
while(!kbhit())
{
temp=random(255);
for(i=0,j=0;i<4000;i+=2)
{
if(j>temp)
j=1;
else j++;
*(vm+i+1)=j;
}
delay(150);
}
return 0;
}
#include<stdlib.h>
int main(void)
{
char far *vm=0xB8000000;
int i,j,temp;
_setcursortype(0);
gotoxy(17,24);
clrscr();
while(!kbhit())
{
temp=random(255);
for(i=0,j=0;i<4000;i+=2)
{
if(j>temp)
j=1;
else j++;
*(vm+i+1)=j;
}
delay(150);
}
return 0;
}
dancing dol
#include<stdio.h>#include<dos.h>
int main(void){char far *vm=0xB8000000;int i;_setcursortype(0);/*printf("Hi fOlKs I hAvE wRiTtEn A pRoGrAm NaMeD \"\" DaNcInG dOlL \"\" ");printf("\n\n\t In ThIs PrOgRaM eVeRy ChArAcTeR iS cHaNgInG iTs CaSe");*/gotoxy(17,24);printf("\"\" DANcing Doll \"\" HeY ItS CooL nAa!!!!!!!!!");while(!kbhit()){for(i=0;i<4000;i+=2){if(islower(*(vm+i)))*(vm+i)-=32;else if(isupper(*(vm+i)))*(vm+i)+=32;}delay(150);}return 0;}
#include<stdio.h>#include<dos.h>
int main(void){char far *vm=0xB8000000;int i;_setcursortype(0);/*printf("Hi fOlKs I hAvE wRiTtEn A pRoGrAm NaMeD \"\" DaNcInG dOlL \"\" ");printf("\n\n\t In ThIs PrOgRaM eVeRy ChArAcTeR iS cHaNgInG iTs CaSe");*/gotoxy(17,24);printf("\"\" DANcing Doll \"\" HeY ItS CooL nAa!!!!!!!!!");while(!kbhit()){for(i=0;i<4000;i+=2){if(islower(*(vm+i)))*(vm+i)-=32;else if(isupper(*(vm+i)))*(vm+i)+=32;}delay(150);}return 0;}
this program first generates the singular link list, and can
1.) reverse the linked list using iteration method
2.) reverse the linked list using recursion method
3.) create link list
4.) display the link list.
*/
#define null NULL
#include<stdio.h>
//-------------------------------------------------------------
// definition of the node
//-------------------------------------------------------------
typedef struct link {
int i;
struct link *next;
}node;
//-------------------------------------------------------------
// link list creation module
//-------------------------------------------------------------
node* create(node* head, int n) {
node* temp, *q;
int i = 0;
// if head is empty
if(!head) {
printf("head is null");
temp = (node*)malloc(sizeof(node));
head = temp;
temp->next = null;
temp->i = 0;
q = head;
}
else { // head is not empty
printf("\nhead is not null");
q = head;
while(q->next != null)
q = q->next;
}
for(i = n; i < n + 5; i++) {
temp = (node*)malloc(sizeof(node));
temp->next = null;
temp->i = i+1;
q->next = temp;
q = temp;
}
return head;
}
//-------------------------------------------------------------
// module to show the given link list head
//-------------------------------------------------------------
void show(node* head) {
while(head != null) {
printf("%d ",head->i);
head = head->next;
}
}
//-------------------------------------------------------------
// reverse the link list using the loop (iteration)
//-------------------------------------------------------------
node* reverse_loop(node* head) {
node *curr, *frwd, *rev;
if(!head)
return null;
rev = curr = null;
frwd = head;
while (frwd != null) {
rev = curr;
curr = frwd;
frwd = frwd->next;
curr->next = rev;
}
return curr;
}
//-------------------------------------------------------------
// reverse the link list using the recursion
//-------------------------------------------------------------
node* reverse_rec(node* head) {
node* temp = null;
if(head->next) {
temp = reverse_rec(head->next);
head->next->next = head;
head->next = null;
return temp;
}
else
return head;
}
void free_linklist(node* head) {
node* temp = null;
while(!head->next) {
temp = head;
head = head->next;
free(temp);
}
}
//-------------------------------------------------------------
// main fxn
//-------------------------------------------------------------
int main() {
node *head = null;
// creation of the link list when head is null(empty)
head = create(head, 0);
// appending to the link list
head = create(head, 10);
printf("\nlink list contains: \n");
show(head);
// reverse the link list using iterations/ loops
head = reverse_loop(head);
printf("\nlink list after reversion contains: \n");
show(head);
// reverse the link list by using recursion
head = reverse_rec(head);
printf("\nlink list after reversion contains: \n");
show(head);
printf("\nfree the link list...");
free_linklist(head);
puts("");
return 0;
}
//-------------------------------------------------------------
// End of the Program..
//-------------------------------------------------------------
1.) reverse the linked list using iteration method
2.) reverse the linked list using recursion method
3.) create link list
4.) display the link list.
*/
#define null NULL
#include<stdio.h>
//-------------------------------------------------------------
// definition of the node
//-------------------------------------------------------------
typedef struct link {
int i;
struct link *next;
}node;
//-------------------------------------------------------------
// link list creation module
//-------------------------------------------------------------
node* create(node* head, int n) {
node* temp, *q;
int i = 0;
// if head is empty
if(!head) {
printf("head is null");
temp = (node*)malloc(sizeof(node));
head = temp;
temp->next = null;
temp->i = 0;
q = head;
}
else { // head is not empty
printf("\nhead is not null");
q = head;
while(q->next != null)
q = q->next;
}
for(i = n; i < n + 5; i++) {
temp = (node*)malloc(sizeof(node));
temp->next = null;
temp->i = i+1;
q->next = temp;
q = temp;
}
return head;
}
//-------------------------------------------------------------
// module to show the given link list head
//-------------------------------------------------------------
void show(node* head) {
while(head != null) {
printf("%d ",head->i);
head = head->next;
}
}
//-------------------------------------------------------------
// reverse the link list using the loop (iteration)
//-------------------------------------------------------------
node* reverse_loop(node* head) {
node *curr, *frwd, *rev;
if(!head)
return null;
rev = curr = null;
frwd = head;
while (frwd != null) {
rev = curr;
curr = frwd;
frwd = frwd->next;
curr->next = rev;
}
return curr;
}
//-------------------------------------------------------------
// reverse the link list using the recursion
//-------------------------------------------------------------
node* reverse_rec(node* head) {
node* temp = null;
if(head->next) {
temp = reverse_rec(head->next);
head->next->next = head;
head->next = null;
return temp;
}
else
return head;
}
void free_linklist(node* head) {
node* temp = null;
while(!head->next) {
temp = head;
head = head->next;
free(temp);
}
}
//-------------------------------------------------------------
// main fxn
//-------------------------------------------------------------
int main() {
node *head = null;
// creation of the link list when head is null(empty)
head = create(head, 0);
// appending to the link list
head = create(head, 10);
printf("\nlink list contains: \n");
show(head);
// reverse the link list using iterations/ loops
head = reverse_loop(head);
printf("\nlink list after reversion contains: \n");
show(head);
// reverse the link list by using recursion
head = reverse_rec(head);
printf("\nlink list after reversion contains: \n");
show(head);
printf("\nfree the link list...");
free_linklist(head);
puts("");
return 0;
}
//-------------------------------------------------------------
// End of the Program..
//-------------------------------------------------------------
factorial using recursion and iteration/loops in C language
#include<stdio.h>
int fib_rec(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fib_rec(n - 1) + fib_rec(n - 2));
}
int fib_loop(int n) {
int a, b, sum;
a = b = sum = 0;
b = 1;
if (n <= 0)
return 0;
else if(n == 1 '' n == 2)
return 1;
while(n > 1) {
sum = a + b;
a = b;
b = sum;
n--;
}
return sum;
}
int main() {
int i, n = 37;
printf("the fib upto %d using recursion is: \n",n);
for(i = 0; i < n; i++)
printf("%d, ",fib_loop(i));
printf("\nthe fib upto %d using loop is: \n",n);
for(i = 0; i < n; i++)
printf("%d, ",fib_rec(i));
puts("");
return 0;
}
#include<stdio.h>
int fib_rec(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fib_rec(n - 1) + fib_rec(n - 2));
}
int fib_loop(int n) {
int a, b, sum;
a = b = sum = 0;
b = 1;
if (n <= 0)
return 0;
else if(n == 1 '' n == 2)
return 1;
while(n > 1) {
sum = a + b;
a = b;
b = sum;
n--;
}
return sum;
}
int main() {
int i, n = 37;
printf("the fib upto %d using recursion is: \n",n);
for(i = 0; i < n; i++)
printf("%d, ",fib_loop(i));
printf("\nthe fib upto %d using loop is: \n",n);
for(i = 0; i < n; i++)
printf("%d, ",fib_rec(i));
puts("");
return 0;
}
C calendar from 1752
#include<stdio.h>
#define Y 1752
//1/1/1752 Saturday
/* the The calendar as we know it only came into effect (inEngland ) in 1752,
replacing the Julian calendar. Changes included cutting 11 or more days out
of the calendar and changing the first day of the year from march 21st to January 1st,
and so this calculation method should not be used for dates before this changeover.
*/
#define BASE 5
void day(int dd, int mm, int yy);
void display(int, int);
int _MONTH[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
char *days[] = {"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday"};
int main() {
char ch = 'y';
int mm,yy,dd;
do {
printf("\nEnter dd ");
scanf("%ld",&dd);
printf("\nEnter mm [1-12] ");
scanf("%ld",&mm);
printf("Enter yyyy ");
scanf("%ld",&yy);
if( (yy%4==0) && ( (yy%100!=0) '' (yy%400==0) ) )
_MONTH[2]=29;
day(dd,mm,yy);
printf("\n\n\n\nPress 'x' to EXIT\n");
fflush(stdin);
ch = getchar();
}while(ch != 'x');
return 0;
}
void day(int dd,int mm, int yy) {
int i,md=0,leap=0,track, temp;
unsigned int d,yrd;
for(i=Y;i<yy;i++) {
if( (i%4==0) && ((i%100!=0) '' (i%400==0)))
leap++;
}
for(i=1; i < mm; i++)
md = md + _MONTH[i];
yrd = (yy-Y) * 365;
d=yrd+leap+md+BASE;
temp = d + dd;
temp = temp % 7;
printf("day is : %s",days[temp]);
track=d%7;
display(track,mm);
}
void display(int track,int m) {
int dt,loop;
printf("\n\n\n\t\t");
printf("MON\tTUES\tWED\tTHURS\tFRI\tSAT\tSUN\n\n");
for(loop=0; loop < track + 2; loop++) /*t+2 due to two additional \t*/
printf("\t");
for(dt=1; dt <= _MONTH[m]; dt++) {
if(track % 7 == 0 && track != 0)
printf("\n\n\t\t");
printf("%d",dt);
printf("\t");
track++;
}
}
#include<stdio.h>
#define Y 1752
//
/* the The calendar as we know it only came into effect (in
replacing the Julian calendar. Changes included cutting 11 or more days out
of the calendar and changing the first day of the year from march 21st to January 1st,
and so this calculation method should not be used for dates before this changeover.
*/
#define BASE 5
void day(int dd, int mm, int yy);
void display(int, int);
int _MONTH[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
char *days[] = {"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday"};
int main() {
char ch = 'y';
int mm,yy,dd;
do {
printf("\nEnter dd ");
scanf("%ld",&dd);
printf("\nEnter mm [1-12] ");
scanf("%ld",&mm);
printf("Enter yyyy ");
scanf("%ld",&yy);
if( (yy%4==0) && ( (yy%100!=0) '' (yy%400==0) ) )
_MONTH[2]=29;
day(dd,mm,yy);
printf("\n\n\n\nPress 'x' to EXIT\n");
fflush(stdin);
ch = getchar();
}while(ch != 'x');
return 0;
}
void day(int dd,int mm, int yy) {
int i,md=0,leap=0,track, temp;
unsigned int d,yrd;
for(i=Y;i<yy;i++) {
if( (i%4==0) && ((i%100!=0) '' (i%400==0)))
leap++;
}
for(i=1; i < mm; i++)
md = md + _MONTH[i];
yrd = (yy-Y) * 365;
d=yrd+leap+md+BASE;
temp = d + dd;
temp = temp % 7;
printf("day is : %s",days[temp]);
track=d%7;
display(track,mm);
}
void display(int track,int m) {
int dt,loop;
printf("\n\n\n\t\t");
printf("MON\tTUES\tWED\tTHURS\tFRI\tSAT\tSUN\n\n");
for(loop=0; loop < track + 2; loop++) /*t+2 due to two additional \t*/
printf("\t");
for(dt=1; dt <= _MONTH[m]; dt++) {
if(track % 7 == 0 && track != 0)
printf("\n\n\t\t");
printf("%d",dt);
printf("\t");
track++;
}
}
DIGITAL CLOCK in C
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#include <dos.h>
#define PI 3.14
void getTime(int *h, int *m, int *s ){
struct time t;
gettime(&t);
gotoxy(36,18);
printf("%2d:%02d:%02d.%02d\n",
t.ti_hour,t.ti_min,t.ti_sec,t.ti_hund);
*h = t.ti_hour;
*m = t.ti_min;
*s = t.ti_sec;
}
void main(){
int gd=DETECT, gm;
initgraph(&gd, &gm, "\\tc");
int xs, ys, xm, ym, xh, yh, h, m, s;
while(!kbhit()){
cleardevice();
getTime(&h, &m, &s);
settextstyle(1,0,0);
setcolor(WHITE);
outtextxy(300,15,"12");
outtextxy(315,425,"6");
outtextxy(105,220,"9");
outtextxy(520,220,"3");
settextstyle(5,0,0);
setcolor(GREEN);
outtextxy(275,300,"CLOCK");
settextstyle(2 ,0,0);
setcolor(LIGHTRED);
outtextxy(310,295,"Mukesh");
xh = cos((h*30 + m / 2) * PI / 180 - PI / 2) * 150 + 320;
yh = sin((h*30 + m / 2) * PI / 180 - PI / 2) * 150 + 240;
xm = cos(m * PI / 30 - PI / 2) * 180 + 320;
ym = sin(m * PI / 30 - PI / 2) * 180 + 240;
xs = cos(s * PI / 30 - PI / 2) * 210 + 320;
ys = sin(s * PI / 30 - PI / 2) * 210 + 240;
setcolor(LIGHTBLUE);
circle(320,240,220);
setcolor(LIGHTRED);
line(320,240,xh,yh);
setcolor(LIGHTGREEN);
line(320,240,xm,ym);
setcolor(YELLOW);
line(320,240,xs,ys);
sleep(1);
}
}
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#include <dos.h>
#define PI 3.14
void getTime(int *h, int *m, int *s ){
struct time t;
gettime(&t);
gotoxy(36,18);
printf("%2d:%02d:%02d.%02d\n",
t.ti_hour,t.ti_min,t.ti_sec,t.ti_hund);
*h = t.ti_hour;
*m = t.ti_min;
*s = t.ti_sec;
}
void main(){
int gd=DETECT, gm;
initgraph(&gd, &gm, "\\tc");
int xs, ys, xm, ym, xh, yh, h, m, s;
while(!kbhit()){
cleardevice();
getTime(&h, &m, &s);
settextstyle(1,0,0);
setcolor(WHITE);
outtextxy(300,15,"12");
outtextxy(315,425,"6");
outtextxy(105,220,"9");
outtextxy(520,220,"3");
settextstyle(5,0,0);
setcolor(GREEN);
outtextxy(275,300,"CLOCK");
settextstyle(2 ,0,0);
setcolor(LIGHTRED);
outtextxy(310,295,"Mukesh");
xh = cos((h*30 + m / 2) * PI / 180 - PI / 2) * 150 + 320;
yh = sin((h*30 + m / 2) * PI / 180 - PI / 2) * 150 + 240;
xm = cos(m * PI / 30 - PI / 2) * 180 + 320;
ym = sin(m * PI / 30 - PI / 2) * 180 + 240;
xs = cos(s * PI / 30 - PI / 2) * 210 + 320;
ys = sin(s * PI / 30 - PI / 2) * 210 + 240;
setcolor(LIGHTBLUE);
circle(320,240,220);
setcolor(LIGHTRED);
line(320,240,xh,yh);
setcolor(LIGHTGREEN);
line(320,240,xm,ym);
setcolor(YELLOW);
line(320,240,xs,ys);
sleep(1);
}
}
set password in c++
#include<iostream.h>
#include<conio.h>
void main()
{
int i=0;
char *pass[10],*pass="name";
cout<<"Enter the password:";
goto start:
pass[i]=getch();
putch('*');
if(pass[i]!=13)
{
i++;
goto start;
}
cout<<"your password is"<<pass;
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i=0;
char *pass[10],*pass="name";
cout<<"Enter the password:";
goto start:
pass[i]=getch();
putch('*');
if(pass[i]!=13)
{
i++;
goto start;
}
cout<<"your password is"<<pass;
getch();
}
Digital Clock
#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<graphics.h>
#include<stdlib.h>
void main()
{
int i=23,j=58,k,l,a=2;
mat:
for(;;i++)
{for(;j<60;j++)
{for(k=0;k<60;k++)
{
l=1;
//settextstyle(triplex_font,horiz dir,a)
printf("%d:%d:%d",i,j,k);
printf("\nif u want to exit press Q");
sleep(l);
clrscr();
if(i==23&&j==59&&k==59)
{
i=0;j=0;k=0;
goto mat;
}
}}}
max:
getch();
}
#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<graphics.h>
#include<stdlib.h>
void main()
{
int i=23,j=58,k,l,a=2;
mat:
for(;;i++)
{for(;j<60;j++)
{for(k=0;k<60;k++)
{
l=1;
//settextstyle(triplex_font,horiz dir,a)
printf("%d:%d:%d",i,j,k);
printf("\nif u want to exit press Q");
sleep(l);
clrscr();
if(i==23&&j==59&&k==59)
{
i=0;j=0;k=0;
goto mat;
}
}}}
max:
getch();
}
reboot the system
#include <dos.h>
void bootme(int want_warm) /* arg 0 = cold boot, 1 = warm */
{
union REGS reg;
void (far* boot)(void) = (void (far*)(void))0xFFFF0000UL;
unsigned far* boottype = (unsigned far*)0x00400072UL;
char far* shiftstate = (char far*)0x00400017UL;
unsigned ticks;
int time_to_waste;
/* Simulate reception of Ctrl-Alt-Del: */
for (;;)
{
*shiftstate '= 0x0C; /* turn on Ctrl & Alt */
reg.h.ah = 0x4F; /* see notes below */
reg.h.al = 0x53; /* 0x53 =Del 's scan code */
reg.x.cflag = 1; /* sentinel for ignoring key */
int86(0x15, ®, ®);
/* If carry flag is still set, we've finished. */
if(reg.x.cflag)
break;
/* Else waste some time before trying again: */
reg.h.ah = 0;
int86(0x1A, ®, ®); /* system time into CX:DX */
ticks = reg.x.dx;
for (time_to_waste = 3; time_to_waste > 0; )
{
reg.h.ah = 0;
int86(0x1A, ®, ®);
if (ticks != reg.x.dx)
ticks = reg.x.dx , --time_to_waste;
}
}
/* Issue a DOS disk reset request: */
reg.h.ah = 0x0D;
int86(0x21, ®, ®);
/* Set boot type and boot: */
*boottype = (want_warm ? 0x1234 : 0);
(*boot)( );
}
void main()
{
bootme(0);
}
#include <dos.h>
void bootme(int want_warm) /* arg 0 = cold boot, 1 = warm */
{
union REGS reg;
void (far* boot)(void) = (void (far*)(void))0xFFFF0000UL;
unsigned far* boottype = (unsigned far*)0x00400072UL;
char far* shiftstate = (char far*)0x00400017UL;
unsigned ticks;
int time_to_waste;
/* Simulate reception of Ctrl-Alt-Del: */
for (;;)
{
*shiftstate '= 0x0C; /* turn on Ctrl & Alt */
reg.h.ah = 0x4F; /* see notes below */
reg.h.al = 0x53; /* 0x53 =
reg.x.cflag = 1; /* sentinel for ignoring key */
int86(0x15, ®, ®);
/* If carry flag is still set, we've finished. */
if(reg.x.cflag)
break;
/* Else waste some time before trying again: */
reg.h.ah = 0;
int86(0x1A, ®, ®); /* system time into CX:DX */
ticks = reg.x.dx;
for (time_to_waste = 3; time_to_waste > 0; )
{
reg.h.ah = 0;
int86(0x1A, ®, ®);
if (ticks != reg.x.dx)
ticks = reg.x.dx , --time_to_waste;
}
}
/* Issue a DOS disk reset request: */
reg.h.ah = 0x0D;
int86(0x21, ®, ®);
/* Set boot type and boot: */
*boottype = (want_warm ? 0x1234 : 0);
(*boot)( );
}
void main()
{
bootme(0);
}
calender
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<dos.h>
class calendar
{ private:
struct cal
{ int month,day;
} c;
int a[12];
char months[12][15];
public:
int choice,yr;
calendar(); //constructor
void menu();
void display();
void manipulate();
void firstshow();
} ;
//end of class calendar
/* Constructor for initializing the number of days of each month */
calendar::calendar()
{ a[0]=31; a[1]=28; a[2]=31; a[3]=30; a[4]=31; a[5]=30;
a[6]=31; a[7]=31; a[8]=30; a[9]=31; a[10]=30; a[11]=31;
char* yr_month[12]=
{ " JANUARY"," FEBRUARY"," MARCH"," APRIL"," MAY",
" JUNE"," JULY"," AUGUST"," SEPTEMBER","OCTOBER",
"NOVEMBER","DECEMBER"};
for(int j=0;j<12;j++)
strcpy(months[j],yr_month[j]);
}
/* Displays the list of months */
void calendar::menu()
{cout<<"\n\t\t\t.............................\n\n";
cout<<"\t\t\tSELECT A MONTH FROM THIS LIST\n\n";
for(int i=0;i<12;i++)
cout<<"\n\t < "<<i+1<<" > "<<months[i];
cout<<endl;
cout<<"\n\t < 0 > Exit to the main screen\n";
cout<<"\n\tPlz type the corresponding no. : ";
cin>>choice;
if (choice>12)
{ cout<<"\n\tWRONG CHOICE!TRY AGAIN!!";
delay(1010);
clrscr();
menu();
}
}
/* This function is used to find out which day is the 1st of each month
using the data 1 Jan 2001 ---> Monday */
void calendar::manipulate()
{ c.month=1;
c.day=2;
int y=yr-2001;
if (yr%4==0) a[1]=29;
for(int i=0;i<y;i++)
{if((2001+i)%4==0){ c.day=c.day+2; }
else{ c.day=c.day+1; }
}
for(i=0;i<(choice-1);i++)
{ int x=a[i]%7;
c.day=c.day+x;
}
if (c.day>7)c.day=c.day%7;
if(c.day==0)c.day=7;
}
/*Function for accepting the year */
void calendar::firstshow()
{ clrscr();
cout<<"\n\n\n\n\tTHIS SOFTWARE DISPLAYS THE CALENDER FOR ANY YEAR B/W";
cout<<"\n\t.....................................................";
cout<<"\n\t\t\t\t2001 - 2099\n";
cout<<"\t\t\t\t............\n";
cout<<"\n\n\tPress '0' to exit";
cout<<"\n\n\tPlz type the year : ";
cin>>yr;
if (yr!=0)
{ //exception handling
if((yr>2099)''(yr<2001))
{cout<<"\n\n\tPLEASE TYPE IN A YEAR AS SPECIFIED ABOVE\n";
delay(1100);
clrscr();
firstshow();
}
}
}
/* Function for displaying the calendar for that particular month */
void calendar::display()
{ cout<<"\n\n\t\tCALENDER FOR "<<months[choice-1]<<""<<yr<<"\n";
cout<<"\t\t..................................";
cout<<"\n\n\n\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT\n\n";
int k=0;
for(int j=1;j<c.day;j++)
{cout<<"\t ";
k++;
}
for(int i=1;i<=a[choice-1];i++)
{ cout<<"\t"<<i;
k++;
if(k==7) { cout<<"\n\n"; k=0; }
}
}
void main()
{clrscr();
calendar cal;
//object creation for calendar class
cal.yr=2001;
cal.firstshow();
while (cal.yr!=0)
{clrscr();
cal.menu();
while(cal.choice!=0)
{cal.manipulate();
clrscr();
cal.display();
getch();
clrscr();
cal.menu();
}
cal.firstshow();
}
}
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<dos.h>
class calendar
{ private:
struct cal
{ int month,day;
} c;
int a[12];
char months[12][15];
public:
int choice,yr;
calendar(); //constructor
void menu();
void display();
void manipulate();
void firstshow();
} ;
//end of class calendar
/* Constructor for initializing the number of days of each month */
calendar::calendar()
{ a[0]=31; a[1]=28; a[2]=31; a[3]=30; a[4]=31; a[5]=30;
a[6]=31; a[7]=31; a[8]=30; a[9]=31; a[10]=30; a[11]=31;
char* yr_month[12]=
{ " JANUARY"," FEBRUARY"," MARCH"," APRIL"," MAY",
" JUNE"," JULY"," AUGUST"," SEPTEMBER","OCTOBER",
"NOVEMBER","DECEMBER"};
for(int j=0;j<12;j++)
strcpy(months[j],yr_month[j]);
}
/* Displays the list of months */
void calendar::menu()
{cout<<"\n\t\t\t.............................\n\n";
cout<<"\t\t\tSELECT A MONTH FROM THIS LIST\n\n";
for(int i=0;i<12;i++)
cout<<"\n\t < "<<i+1<<" > "<<months[i];
cout<<endl;
cout<<"\n\t < 0 > Exit to the main screen\n";
cout<<"\n\tPlz type the corresponding no. : ";
cin>>choice;
if (choice>12)
{ cout<<"\n\tWRONG CHOICE!TRY AGAIN!!";
delay(1010);
clrscr();
menu();
}
}
/* This function is used to find out which day is the 1st of each month
using the data 1 Jan 2001 ---> Monday */
void calendar::manipulate()
{ c.month=1;
c.day=2;
int y=yr-2001;
if (yr%4==0) a[1]=29;
for(int i=0;i<y;i++)
{if((2001+i)%4==0){ c.day=c.day+2; }
else{ c.day=c.day+1; }
}
for(i=0;i<(choice-1);i++)
{ int x=a[i]%7;
c.day=c.day+x;
}
if (c.day>7)c.day=c.day%7;
if(c.day==0)c.day=7;
}
/*Function for accepting the year */
void calendar::firstshow()
{ clrscr();
cout<<"\n\n\n\n\tTHIS SOFTWARE DISPLAYS THE CALENDER FOR ANY YEAR B/W";
cout<<"\n\t.....................................................";
cout<<"\n\t\t\t\t2001 - 2099\n";
cout<<"\t\t\t\t............\n";
cout<<"\n\n\tPress '0' to exit";
cout<<"\n\n\tPlz type the year : ";
cin>>yr;
if (yr!=0)
{ //exception handling
if((yr>2099)''(yr<2001))
{cout<<"\n\n\tPLEASE TYPE IN A YEAR AS SPECIFIED ABOVE\n";
delay(1100);
clrscr();
firstshow();
}
}
}
/* Function for displaying the calendar for that particular month */
void calendar::display()
{ cout<<"\n\n\t\tCALENDER FOR "<<months[choice-1]<<""<<yr<<"\n";
cout<<"\t\t..................................";
cout<<"\n\n\n\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT\n\n";
int k=0;
for(int j=1;j<c.day;j++)
{cout<<"\t ";
k++;
}
for(int i=1;i<=a[choice-1];i++)
{ cout<<"\t"<<i;
k++;
if(k==7) { cout<<"\n\n"; k=0; }
}
}
void main()
{clrscr();
calendar cal;
//object creation for calendar class
cal.yr=2001;
cal.firstshow();
while (cal.yr!=0)
{clrscr();
cal.menu();
while(cal.choice!=0)
{cal.manipulate();
clrscr();
cal.display();
getch();
clrscr();
cal.menu();
}
cal.firstshow();
}
}
heap of circles
// PROGRAM TO MAKE A HEAP OF CIRCLES
#include<graphics.h>
#include<conio.h>
#include<stdio.h>
#include<dos.h>
void main()
{
int gd=DETECT,gm,n;
void draw(int);
char ch;
initgraph(&gd,&gm,"");
start:
cleardevice();
gotoxy(20,5);
printf("enter the no of circles you want to draw : ");
scanf("%d",&n);
if(n<=1)
{
puts("\n\n\t\tplz enter the number greater than 1 ");
getch();
goto start;
}
draw(n);
gotoxy(2,1);
printf("\n\twant more ? Press ENTER for YES ");
ch=getch();
if(ch==13)
goto start;
closegraph();
}
void draw(int n)
{
int x,y,midx,midy,x1,i,j,no=1;
cleardevice();
midx=getmaxx()/2;
midy=60;
y=midy;
setfillstyle(1,2);
for(;n>0;n--)
{
x=x1=midx;
i=j=no;
delay(200-n);
for(;i>0;i--)
{
circle(x1,y,10); //left
floodfill(x1,y,15);
x1-=20;
}
for(;j>0;j--)
{
circle(x,y,10); //right
floodfill(x,y,15);
x+=20;
}
no++;
y+=20;
}
}
// PROGRAM TO MAKE A HEAP OF CIRCLES
#include<graphics.h>
#include<conio.h>
#include<stdio.h>
#include<dos.h>
void main()
{
int gd=DETECT,gm,n;
void draw(int);
char ch;
initgraph(&gd,&gm,"");
start:
cleardevice();
gotoxy(20,5);
printf("enter the no of circles you want to draw : ");
scanf("%d",&n);
if(n<=1)
{
puts("\n\n\t\tplz enter the number greater than 1 ");
getch();
goto start;
}
draw(n);
gotoxy(2,1);
printf("\n\twant more ? Press ENTER for YES ");
ch=getch();
if(ch==13)
goto start;
closegraph();
}
void draw(int n)
{
int x,y,midx,midy,x1,i,j,no=1;
cleardevice();
midx=getmaxx()/2;
midy=60;
y=midy;
setfillstyle(1,2);
for(;n>0;n--)
{
x=x1=midx;
i=j=no;
delay(200-n);
for(;i>0;i--)
{
circle(x1,y,10); //left
floodfill(x1,y,15);
x1-=20;
}
for(;j>0;j--)
{
circle(x,y,10); //right
floodfill(x,y,15);
x+=20;
}
no++;
y+=20;
}
}
draw a hut in graphics
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm," ");
cleardevice();
fflush(stdout);
line(200,150,350,150);
line(140,200,200,150);
line(140,330,140,200);
line(250,200,140,200);
line(200,150,250,200);
circle(196,180,8);
setfillstyle(2,4);
floodfill(196,180,15);
setfillstyle(1,2);
line(350,150,400,200);
floodfill(210,180,15);
line(400,200,400,330);
line(140,330,400,330);
line(250,200,250,330);
line(250,200,400,200); //hut
setfillstyle(5,7);
floodfill(260,180,15);
line(170,260,170,330);
line(170,260,210,260);
setfillstyle(10,9);
floodfill(180,250,15);
line(210,260,210,330);
setfillstyle(9,9);
floodfill(210,250,15);
line(290,110,290,150);
line(310,110,310,150);
ellipse(300,110,0,360,10,3); //chimney
setfillstyle(6,8);
floodfill(300,120,15);
line(300,250,350,250);
line(300,280,350,280);
line(350,250,350,280);
line(300,280,300,250);
setfillstyle(9,9);
floodfill(252,300,15);
setfillstyle(8,9);
floodfill(342,270,15);
setcolor(4);
settextstyle(7,0,5);
outtextxy(100,390,"Home Sweet Home");
getch();
closegraph();
}
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm," ");
cleardevice();
fflush(stdout);
line(200,150,350,150);
line(140,200,200,150);
line(140,330,140,200);
line(250,200,140,200);
line(200,150,250,200);
circle(196,180,8);
setfillstyle(2,4);
floodfill(196,180,15);
setfillstyle(1,2);
line(350,150,400,200);
floodfill(210,180,15);
line(400,200,400,330);
line(140,330,400,330);
line(250,200,250,330);
line(250,200,400,200); //hut
setfillstyle(5,7);
floodfill(260,180,15);
line(170,260,170,330);
line(170,260,210,260);
setfillstyle(10,9);
floodfill(180,250,15);
line(210,260,210,330);
setfillstyle(9,9);
floodfill(210,250,15);
line(290,110,290,150);
line(310,110,310,150);
ellipse(300,110,0,360,10,3); //chimney
setfillstyle(6,8);
floodfill(300,120,15);
line(300,250,350,250);
line(300,280,350,280);
line(350,250,350,280);
line(300,280,300,250);
setfillstyle(9,9);
floodfill(252,300,15);
setfillstyle(8,9);
floodfill(342,270,15);
setcolor(4);
settextstyle(7,0,5);
outtextxy(100,390,"Home Sweet Home");
getch();
closegraph();
}
example of a full class declaration
//Here is an example of a full class declaration :
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double = 0, double = 0);
vector operator + (vector);
vector operator - (vector);
vector operator - ();
vector operator * (double a);
double module();
void set_length (double = 1);
};
vector::vector (double a, double b)
{
x = a;
y = b;
}
vector vector::operator + (vector a)
{
return vector (x + a.x, y + a.y);
}
vector vector::operator - (vector a)
{
return vector (x - a.x, y - a.y);
}
vector vector::operator - ()
{
return vector (-x, -y);
}
vector vector::operator * (double a)
{
return vector (x * a, y * a);
}
double vector::module()
{
return sqrt (x * x + y * y);
}
void vector::set_length (double a)
{
double length = this->module();
x = x / length * a;
y = y / length * a;
}
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}
void main ()
{
vector a;
vector b;
vector c (3, 5);
a = c * 3;
a = b + c;
c = b - c + a + (b - a) * 7;
c = -c;
cout << "The module of vector c : " << c.module() << endl;
cout << "The content of vector a : " << a << endl;
cout << "The oposite of vector a : " << -a << endl;
c.set_length(2); // Transforms c in a vector of size 2.
a = vector (56, -3);
b = vector (7, c.y);
b.set_length(); // Transforms b in an unitary vector.
cout << "The content of vector b : " << b << endl;
double k;
k = vector(1, 1).module(); // k will contain 1.4142.
cout << "k contains : " << k << endl;
}
//Here is an example of a full class declaration :
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double = 0, double = 0);
vector operator + (vector);
vector operator - (vector);
vector operator - ();
vector operator * (double a);
double module();
void set_length (double = 1);
};
vector::vector (double a, double b)
{
x = a;
y = b;
}
vector vector::operator + (vector a)
{
return vector (x + a.x, y + a.y);
}
vector vector::operator - (vector a)
{
return vector (x - a.x, y - a.y);
}
vector vector::operator - ()
{
return vector (-x, -y);
}
vector vector::operator * (double a)
{
return vector (x * a, y * a);
}
double vector::module()
{
return sqrt (x * x + y * y);
}
void vector::set_length (double a)
{
double length = this->module();
x = x / length * a;
y = y / length * a;
}
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}
void main ()
{
vector a;
vector b;
vector c (3, 5);
a = c * 3;
a = b + c;
c = b - c + a + (b - a) * 7;
c = -c;
cout << "The module of vector c : " << c.module() << endl;
cout << "The content of vector a : " << a << endl;
cout << "The oposite of vector a : " << -a << endl;
c.set_length(2); // Transforms c in a vector of size 2.
a = vector (56, -3);
b = vector (7, c.y);
b.set_length(); // Transforms b in an unitary vector.
cout << "The content of vector b : " << b << endl;
double k;
k = vector(1, 1).module(); // k will contain 1.4142.
cout << "k contains : " << k << endl;
}
declare arrays of objects
// it is possible to declare arrays of objects :
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double module ()
{
return sqrt (x * x + y * y);
}
};
void main ()
{
vector s[1000];
vector t[3] = {vector(4, 5), vector(5, 5), vector(2, 4)};
s[23] = t[2];
cout << t[0].module() << endl;
}
// it is possible to declare arrays of objects :
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double module ()
{
return sqrt (x * x + y * y);
}
};
void main ()
{
vector s[1000];
vector t[3] = {vector(4, 5), vector(5, 5), vector(2, 4)};
s[23] = t[2];
cout << t[0].module() << endl;
}
programme for constructor "vector" with arguments
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double module()
{
return sqrt (x * x + y * y);
}
void set_length (double a = 1)
{
double length;
length = this->module();
x = x / length * a;
y = y / length * a;
}
};
void main ()
{
vector c (3, 5);
cout << "The module of vector c : " << c.module() << endl;
c.set_length(2); // Transforms c in a vector of size 2.
cout << "The module of vector c : " << c.module() << endl;
c.set_length(); // Transforms b in an unitary vector.
cout << "The module of vector c : " << c.module() << endl;
}
#include <iostream.h>
#include <math.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
double module()
{
return sqrt (x * x + y * y);
}
void set_length (double a = 1)
{
double length;
length = this->module();
x = x / length * a;
y = y / length * a;
}
};
void main ()
{
vector c (3, 5);
cout << "The module of vector c : " << c.module() << endl;
c.set_length(2); // Transforms c in a vector of size 2.
cout << "The module of vector c : " << c.module() << endl;
c.set_length(); // Transforms b in an unitary vector.
cout << "The module of vector c : " << c.module() << endl;
}
programme on class "vector" with information:The ; and no {} shows a prototype
#include <iostream.h>
class vector
{
public:
double x;
double y;
double surface(); // The ; and no {} shows it is a prototype
};
double vector::surface()
{
double s = 0;
for (double i = 0; i < x; i++)
{
s = s + y;
}
return s;
}
void main ()
{
vector k;
k.x = 4;
k.y = 5;
cout << "Surface : " << k.surface() << endl;
}
#include <iostream.h>
class vector
{
public:
double x;
double y;
double surface(); // The ; and no {} shows it is a prototype
};
double vector::surface()
{
double s = 0;
for (double i = 0; i < x; i++)
{
s = s + y;
}
return s;
}
void main ()
{
vector k;
k.x = 4;
k.y = 5;
cout << "Surface : " << k.surface() << endl;
}
a programme for starting knowledge about The COPY CONSTRUCTOR
#include<iostream.h>
#include <string.h>
class person
{
public:
char *name;
int age;
person (char *n = "no name", int a = 0)
{
name = new char[100];
strcpy (name, n);
age = a;
}
person (person &s) // The COPY CONSTRUCTOR
{
strcpy (name, s.name);
age = s.age;
}
~person ()
{
delete (name);
}
};
void main ()
{
person p;
cout << p.name << ", age " << p.age << endl << endl;
person k ("John", 56);
cout << k.name << ", age " << k.age << endl << endl;
p = k;
cout << p.name << ", age " << p.age << endl << endl;
p = person ("Bob", 10);
cout << p.name << ", age " << p.age << endl << endl;
}
#include<iostream.h>
#include <string.h>
class person
{
public:
char *name;
int age;
person (char *n = "no name", int a = 0)
{
name = new char[100];
strcpy (name, n);
age = a;
}
person (person &s) // The COPY CONSTRUCTOR
{
strcpy (name, s.name);
age = s.age;
}
~person ()
{
delete (name);
}
};
void main ()
{
person p;
cout << p.name << ", age " << p.age << endl << endl;
person k ("John", 56);
cout << k.name << ", age " << k.age << endl << endl;
p = k;
cout << p.name << ", age " << p.age << endl << endl;
p = person ("Bob", 10);
cout << p.name << ", age " << p.age << endl << endl;
}
in case of dynamic memory allocation ::new is better than malloc
#include <iostream.h>
#include <string.h>
class person
{
public:
char *name;
int age;
person (char *n = "no name", int a = 0)
{
name = new char[100]; // better than malloc !
strcpy (name, n);
age = a;
cout << "Instance initialized, 100 bytes allocated" << endl;
}
~person () // The destructor
{
delete (name); // instead of free !
cout << "Instance going to be deleted, 100 bytes freed" << endl;
}
};
void main ()
{
cout << "Hello !" << endl << endl;
person a;
cout << a.name << ", age " << a.age << endl << endl;
person b ("John");
cout << b.name << ", age " << b.age << endl << endl;
b.age = 21;
cout << b.name << ", age " << b.age << endl << endl;
person c ("Miki", 45);
cout << c.name << ", age " << c.age << endl << endl;
cout << "Bye !" << endl << endl;
}
#include <iostream.h>
#include <string.h>
class person
{
public:
char *name;
int age;
person (char *n = "no name", int a = 0)
{
name = new char[100]; // better than malloc !
strcpy (name, n);
age = a;
cout << "Instance initialized, 100 bytes allocated" << endl;
}
~person () // The destructor
{
delete (name); // instead of free !
cout << "Instance going to be deleted, 100 bytes freed" << endl;
}
};
void main ()
{
cout << "Hello !" << endl << endl;
person a;
cout << a.name << ", age " << a.age << endl << endl;
person b ("John");
cout << b.name << ", age " << b.age << endl << endl;
b.age = 21;
cout << b.name << ", age " << b.age << endl << endl;
person c ("Miki", 45);
cout << c.name << ", age " << c.age << endl << endl;
cout << "Bye !" << endl << endl;
}
declare only one constructor and give it default parameters wherever possible instead of overloading constructors
//It is a good practice to try not to overload the constructors.
//Best is to declare only one constructor and give it default parameters
//wherever possible :
#include <iostream.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
};
void main ()
{
vector k;
cout << "vector k : " << k.x << ", " << k.y << endl << endl;
vector m (45, 2);
cout << "vector m : " << m.x << ", " << m.y << endl << endl;
vector p (3);
cout << "vector p : " << p.x << ", " << p.y << endl << endl;
}
//It is a good practice to try not to overload the constructors.
//Best is to declare only one constructor and give it default parameters
//wherever possible :
#include <iostream.h>
class vector
{
public:
double x;
double y;
vector (double a = 0, double b = 0)
{
x = a;
y = b;
}
};
void main ()
{
vector k;
cout << "vector k : " << k.x << ", " << k.y << endl << endl;
vector m (45, 2);
cout << "vector m : " << m.x << ", " << m.y << endl << endl;
vector p (3);
cout << "vector p : " << p.x << ", " << p.y << endl << endl;
}
example of a class definition with two overloaded constructors
//Here is an example of a class definition with two overloaded constructors.
#include <iostream.h>
class vector
{
public:
double x;
double y;
vector () // same name as class
{
x = 0;
y = 0;
}
vector (double a, double b)
{
x = a;
y = b;
}
};
void main ()
{
vector k; // vector () is called
cout << "vector k : " << k.x << ", " << k.y << endl << endl;
vector m (45, 2); // vector (double, double) is called
cout << "vector m : " << m.x << ", " << m.y << endl << endl;
k = vector (23, 2); // vector created, copied to k, then erased
cout << "vector k : " << k.x << ", " << k.y << endl << endl;
}
//Here is an example of a class definition with two overloaded constructors.
#include <iostream.h>
class vector
{
public:
double x;
double y;
vector () // same name as class
{
x = 0;
y = 0;
}
vector (double a, double b)
{
x = a;
y = b;
}
};
void main ()
{
vector k; // vector () is called
cout << "vector k : " << k.x << ", " << k.y << endl << endl;
vector m (45, 2); // vector (double, double) is called
cout << "vector m : " << m.x << ", " << m.y << endl << endl;
k = vector (23, 2); // vector created, copied to k, then erased
cout << "vector k : " << k.x << ", " << k.y << endl << endl;
}
method is allowed to change the variables of the instance it is acting upon
//A method is allowed to change the variables of the instance it is acting upon :
#include <iostream.h>
class vector
{
public:
double x;
double y;
vector its_oposite()
{
vector r;
r.x = -x;
r.y = -y;
return r;
}
void be_oposited()
{
x = -x;
y = -y;
}
void be_calculated (double a, double b, double c, double d)
{
x = a - c;
y = b - d;
}
vector operator * (double a)
{
vector r;
r.x = x * a;
r.y = y * a;
return r;
}
};
void main (void)
{
vector a, b;
a.x = 3;
b.y = 5;
b = a.its_oposite();
cout << "Vector a : " << a.x << ", " << a.y << endl;
cout << "Vector b : " << b.x << ", " << b.y << endl;
b.be_oposited();
cout << "Vector b : " << b.x << ", " << b.y << endl;
a.be_calculated (7, 8, 3, 2);
cout << "Vector a : " << a.x << ", " << a.y << endl;
a = b * 2;
cout << "Vector a : " << a.x << ", " << a.y << endl;
a = b.its_oposite() * 2;
cout << "Vector a : " << a.x << ", " << a.y << endl;
cout << "x of oposite of a : " << a.its_oposite().x << endl;
}
//A method is allowed to change the variables of the instance it is acting upon :
#include <iostream.h>
class vector
{
public:
double x;
double y;
vector its_oposite()
{
vector r;
r.x = -x;
r.y = -y;
return r;
}
void be_oposited()
{
x = -x;
y = -y;
}
void be_calculated (double a, double b, double c, double d)
{
x = a - c;
y = b - d;
}
vector operator * (double a)
{
vector r;
r.x = x * a;
r.y = y * a;
return r;
}
};
void main (void)
{
vector a, b;
a.x = 3;
b.y = 5;
b = a.its_oposite();
cout << "Vector a : " << a.x << ", " << a.y << endl;
cout << "Vector b : " << b.x << ", " << b.y << endl;
b.be_oposited();
cout << "Vector b : " << b.x << ", " << b.y << endl;
a.be_calculated (7, 8, 3, 2);
cout << "Vector a : " << a.x << ", " << a.y << endl;
a = b * 2;
cout << "Vector a : " << a.x << ", " << a.y << endl;
a = b.its_oposite() * 2;
cout << "Vector a : " << a.x << ", " << a.y << endl;
cout << "x of oposite of a : " << a.its_oposite().x << endl;
}
allocation of memory and deallocation of memory during run-time
#include <iostream.h>
#include <string.h>
void main ()
{
double *d; // d is a variable whose purpose
// is to contain the address of a
// zone where a double is located
d = new double; // new allocates a zone of memory
// large enough to contain a double
// and returns its address.
// That address is stored in d.
*d = 45.3; // The number 45.3 is stored
// inside the memory zone
// whose address is given by d.
cout << "Type a number : ";
cin >> *d;
*d = *d + 5;
cout << "Result : " << *d << endl;
delete (d); // delete deallocates the
// zone of memory whose address
// is given by pointer d.
// Now we can no more use that zone.
d = new double[15]; // allocates a zone for an array
// of 15 doubles
d[0] = 4456;
d[1] = d[0] +567;
cout << "Content of d[1] : " << d[1] << endl;
delete (d);
int n = 30;
d = new double[n]; // new can be used to allocate an
// array of random size.
for (int i = 0; i < n; i++)
{
d[i] = i;
}
delete (d);
char *s;
s = new char[100];
strcpy (s, "Hello !");
cout << s << endl;
delete (s);
}
#include <iostream.h>
#include <string.h>
void main ()
{
double *d; // d is a variable whose purpose
// is to contain the address of a
// zone where a double is located
d = new double; // new allocates a zone of memory
// large enough to contain a double
// and returns its address.
// That address is stored in d.
*d = 45.3; // The number 45.3 is stored
// inside the memory zone
// whose address is given by d.
cout << "Type a number : ";
cin >> *d;
*d = *d + 5;
cout << "Result : " << *d << endl;
delete (d); // delete deallocates the
// zone of memory whose address
// is given by pointer d.
// Now we can no more use that zone.
d = new double[15]; // allocates a zone for an array
// of 15 doubles
d[0] = 4456;
d[1] = d[0] +567;
cout << "Content of d[1] : " << d[1] << endl;
delete (d);
int n = 30;
d = new double[n]; // new can be used to allocate an
// array of random size.
for (int i = 0; i < n; i++)
{
d[i] = i;
}
delete (d);
char *s;
s = new char[100];
strcpy (s, "Hello !");
cout << s << endl;
delete (s);
}
operator overloading of operator"<<"
//operator overloading
#include <iostream.h>
struct vector
{
double x;
double y;
};
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}
void main ()
{
vector a;
a.x = 35;
a.y = 23;
cout << a << endl;
}
//operator overloading
#include <iostream.h>
struct vector
{
double x;
double y;
};
ostream& operator << (ostream& o, vector a)
{
o << "(" << a.x << ", " << a.y << ")";
return o;
}
void main ()
{
vector a;
a.x = 35;
a.y = 23;
cout << a << endl;
}
"operators overload" can be used to define the basic symbolic operators for new sorts of parameters
//The "operators overload" can be used to define the basic
//symbolic operators for new sorts of parameters :
#include <iostream.h>
struct vector
{
double x;
double y;
};
vector operator * (double a, vector b)
{
vector r;
r.x = a * b.x;
r.y = a * b.y;
return r;
}
void main ()
{
vector k, m; // No need to type "struct vector"
k.x = 2; // Keep cool, soon you'll be able
k.y = -1; // to write k = vector (45, -4).
m = 3.1415927 * k; // Magic !
cout << "(" << m.x << ", " << m.y << ")" << endl;
}
//The "operators overload" can be used to define the basic
//symbolic operators for new sorts of parameters :
#include <iostream.h>
struct vector
{
double x;
double y;
};
vector operator * (double a, vector b)
{
vector r;
r.x = a * b.x;
r.y = a * b.y;
return r;
}
void main ()
{
vector k, m; // No need to type "struct vector"
k.x = 2; // Keep cool, soon you'll be able
k.y = -1; // to write k = vector (45, -4).
m = 3.1415927 * k; // Magic !
cout << "(" << m.x << ", " << m.y << ")" << endl;
}
It is possible to define default parameters for functions
//It is possible to define default parameters for functions :
#include <iostream.h>
double test (double a, double b = 7)
{
return a - b;
}
void main ()
{
cout << test (14, 5) << endl;
cout << test (14) << endl;
}
//It is possible to define default parameters for functions :
#include <iostream.h>
double test (double a, double b = 7)
{
return a - b;
}
void main ()
{
cout << test (14, 5) << endl;
cout << test (14) << endl;
}
programme on implementation on queue
//queue
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Queue{
struct Queue *node;
char item[1];
};
struct Queue *volatile q;
int QueueAdd(const char *_item)
{
int _q;
struct Queue *queue;
_q = sizeof(struct Queue) + strlen(_item) + 4;
queue = (struct Queue *)malloc(_q); /* allocate the space in memory we need */
if (queue == 0) return 1;
memset(queue, 0, _q);
strcpy(queue->item, _item);
queue->node = q;
q = queue;
return 0;
}
void printq()
{
struct Queue *qq;
int n,j,num;
n=0;
for (qq=q, num=0; qq; qq=qq->node, num++); /* enumerate items in queue */
if(num==NULL)
{
printf("No items currently in the Queue");
return;
}
printf("Here are the items in the Queue \n");
cycle:
for (j=0,qq=q; (j < n) && qq; qq=qq->node, j++); /* lets hop to the next node */
printf("%s \n",qq->item);
n++;
if(n<num)
goto cycle;
}
int main()
{
struct Queue *qq;
int i,num;
char in[100]; /* array of 100 bytes */
/* print to stdout */
printf("Welcome to the Queue!");
printf("\n Dequeue not implemented \n");
printf("Usage: \n");
input: /* input label */
printf("\n1. Add to the queue\n");
printf("2. Print number of items in Queue \n");
printf("3. Print the items in the Queue \n");
printf("4. Exit the program \n");
scanf("%d",&i); /* check for inputted data */
switch(i)
{
case 1:
printf("Enter Item to add to the Queue \n");
scanf("%s",&in);
QueueAdd(in); /* call 'QueueAdd', let us assume everything goes o.k. */
printf("%s successfully added to the queue",in);
goto input;
break;
case 2:
for (qq=q, num=0; qq; qq=qq->node, num++);
/* Null statement above to enumerate items in the queue */
printf("There are %d items in the queue",num);
goto input;
break;
case 3:
printq();
goto input;
break;
case 4:
printf("Exiting program");
exit(0);
break; /* why not? :) */
default:
printf("Tu esta estupido!");
goto input;
}
}
//queue
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Queue{
struct Queue *node;
char item[1];
};
struct Queue *volatile q;
int QueueAdd(const char *_item)
{
int _q;
struct Queue *queue;
_q = sizeof(struct Queue) + strlen(_item) + 4;
queue = (struct Queue *)malloc(_q); /* allocate the space in memory we need */
if (queue == 0) return 1;
memset(queue, 0, _q);
strcpy(queue->item, _item);
queue->node = q;
q = queue;
return 0;
}
void printq()
{
struct Queue *qq;
int n,j,num;
n=0;
for (qq=q, num=0; qq; qq=qq->node, num++); /* enumerate items in queue */
if(num==NULL)
{
printf("No items currently in the Queue");
return;
}
printf("Here are the items in the Queue \n");
cycle:
for (j=0,qq=q; (j < n) && qq; qq=qq->node, j++); /* lets hop to the next node */
printf("%s \n",qq->item);
n++;
if(n<num)
goto cycle;
}
int main()
{
struct Queue *qq;
int i,num;
char in[100]; /* array of 100 bytes */
/* print to stdout */
printf("Welcome to the Queue!");
printf("\n Dequeue not implemented \n");
printf("Usage: \n");
input: /* input label */
printf("\n1. Add to the queue\n");
printf("2. Print number of items in Queue \n");
printf("3. Print the items in the Queue \n");
printf("4. Exit the program \n");
scanf("%d",&i); /* check for inputted data */
switch(i)
{
case 1:
printf("Enter Item to add to the Queue \n");
scanf("%s",&in);
QueueAdd(in); /* call 'QueueAdd', let us assume everything goes o.k. */
printf("%s successfully added to the queue",in);
goto input;
break;
case 2:
for (qq=q, num=0; qq; qq=qq->node, num++);
/* Null statement above to enumerate items in the queue */
printf("There are %d items in the queue",num);
goto input;
break;
case 3:
printq();
goto input;
break;
case 4:
printf("Exiting program");
exit(0);
break; /* why not? :) */
default:
printf("Tu esta estupido!");
goto input;
}
}
references are very useful to un-pointer variables
//To end with, for people who have to deal with pointers
//yet do not like it, references are very useful to un-pointer variables :
#include <iostream.h>
double *silly_function () // This function returns a pointer to a double
{
static double r = 342;
return &r;
}
void main()
{
double *a;
a = silly_function();
double &b = *a; // Now b IS the double towards which a points !
b += 1; // Great !
b = b * b; // No need to write *a everywhere !
b += 4;
cout << "Content of *a, b, r : " << b << endl;
}
//To end with, for people who have to deal with pointers
//yet do not like it, references are very useful to un-pointer variables :
#include <iostream.h>
double *silly_function () // This function returns a pointer to a double
{
static double r = 342;
return &r;
}
void main()
{
double *a;
a = silly_function();
double &b = *a; // Now b IS the double towards which a points !
b += 1; // Great !
b = b * b; // No need to write *a everywhere !
b += 4;
cout << "Content of *a, b, r : " << b << endl;
}
reference can be used to let a function return a variable
//A reference can be used to let a function return a variable :
#include <iostream.h>
double &biggest (double &r, double &s)
{
if (r > s) return r;
else return s;
}
void main ()
{
double k = 3;
double m = 7;
cout << "k : " << k << endl;
cout << "m : " << m << endl;
cout << endl;
biggest (k, m) = 10;
cout << "k : " << k << endl;
cout << "m : " << m << endl;
cout << endl;
biggest (k, m) ++;
cout << "k : " << k << endl;
cout << "m : " << m << endl;
cout << endl;
}
//A reference can be used to let a function return a variable :
#include <iostream.h>
double &biggest (double &r, double &s)
{
if (r > s) return r;
else return s;
}
void main ()
{
double k = 3;
double m = 7;
cout << "k : " << k << endl;
cout << "m : " << m << endl;
cout << endl;
biggest (k, m) = 10;
cout << "k : " << k << endl;
cout << "m : " << m << endl;
cout << endl;
biggest (k, m) ++;
cout << "k : " << k << endl;
cout << "m : " << m << endl;
cout << endl;
}
an important programme on pointers
//If you are used at pointers in C and wonder how exactly the program
//above works, here is how the C++ compiler translates
#include <iostream.h>
void change (double *r, double s)
{
*r = 100;
s = 200;
}
void main ()
{
double k, m;
k = 3;
m = 4;
change (&k, m);
cout << k << ", " << m << endl; // Displays 100, 4.
}
//If you are used at pointers in C and wonder how exactly the program
//above works, here is how the C++ compiler translates
#include <iostream.h>
void change (double *r, double s)
{
*r = 100;
s = 200;
}
void main ()
{
double k, m;
k = 3;
m = 4;
change (&k, m);
cout << k << ", " << m << endl; // Displays 100, 4.
}
References can be used to allow a function to modify a calling variable
//References can be used to allow a function to modify a calling variable :
#include <iostream.h>
void change (double &r, double s)
{
r = 100;
s = 200;
}
void main ()
{
double k, m;
k = 3;
m = 4;
change (k, m);
cout << k << ", " << m << endl; // Displays 100, 4.
}
//References can be used to allow a function to modify a calling variable :
#include <iostream.h>
void change (double &r, double s)
{
r = 100;
s = 200;
}
void main ()
{
double k, m;
k = 3;
m = 4;
change (k, m);
cout << k << ", " << m << endl; // Displays 100, 4.
}
It is possible to make one variable be another
//It is possible to make one variable be another :
#include <iostream.h>
void main ()
{
double a = 3.1415927;
double &b = a; // b IS a
b = 89;
cout << "a contains : " << a << endl; // Displays 89.
}
//It is possible to make one variable be another :
#include <iostream.h>
void main ()
{
double a = 3.1415927;
double &b = a; // b IS a
b = 89;
cout << "a contains : " << a << endl; // Displays 89.
}
important point on global vs local variable
//A global variable can be accessed even if another variable with the same
//name has been declared inside the function :
#include <iostream.h>
double a = 128;
void main ()
{
double a = 256;
cout << "Local a : " << a << endl;
cout << "Global a : " << ::a << endl;
}
//A global variable can be accessed even if another variable with the same
//name has been declared inside the function :
#include <iostream.h>
double a = 128;
void main ()
{
double a = 256;
cout << "Local a : " << a << endl;
cout << "Global a : " << ::a << endl;
}
important point on variable declaration
//C++ allows to declare a variable inside the for loop declaration.
//It's like if the variable had been declared just before the loop :
#include <iostream.h>
void main ()
{
for (int i = 0; i < 4; i++)
{
cout << i << endl;
}
cout << "i contains : " << i << endl;
for (i = 0; i < 4; i++)
{
for (int i = 0; i < 4; i++) // we're between
{ // previous for's hooks
cout << i;
}
cout << endl;
}
}
//C++ allows to declare a variable inside the for loop declaration.
//It's like if the variable had been declared just before the loop :
#include <iostream.h>
void main ()
{
for (int i = 0; i < 4; i++)
{
cout << i << endl;
}
cout << "i contains : " << i << endl;
for (i = 0; i < 4; i++)
{
for (int i = 0; i < 4; i++) // we're between
{ // previous for's hooks
cout << i;
}
cout << endl;
}
}
Like in C, variables can be encapsulated between hooks
//Like in C, variables can be encapsulated between hooks :
#include <iostream.h>
void main()
{
double a;
cout << "Type a number : ";
cin >> a;
{
int a = 1;
a = a * 10 + 4;
cout << "Local number : " << a << endl;
}
cout << "You typed : " << a << endl;
}
//Like in C, variables can be encapsulated between hooks :
#include <iostream.h>
void main()
{
double a;
cout << "Type a number : ";
cin >> a;
{
int a = 1;
a = a * 10 + 4;
cout << "Local number : " << a << endl;
}
cout << "You typed : " << a << endl;
}
A variable can be initialized by a calculation
//A variable can be initialized by a calculation :
#include <iostream.h>
void main ()
{
double a = 12 * 3.25;
double b = a + 1.112;
cout << "a contains : " << a << endl;
cout << "b contains : " << b << endl;
a = a * 2 + b;
double c = a + b * a;
cout << "c contains : " << c << endl;
}
//A variable can be initialized by a calculation :
#include <iostream.h>
void main ()
{
double a = 12 * 3.25;
double b = a + 1.112;
cout << "a contains : " << a << endl;
cout << "b contains : " << b << endl;
a = a * 2 + b;
double c = a + b * a;
cout << "c contains : " << c << endl;
}
Variables can be declared everywhere
//Variables can be declared everywhere :
#include <iostream.h>
void main ()
{
double a;
cout << "Hello, this is a test program." << endl;
cout << "Type parameter a : ";
cin >> a;
a = (a + 1) / 2;
double c;
c = a * 5 + 1;
cout << "c contains : " << c << endl;
int i, j;
i = 0;
j = i + 1;
cout << "j contains : " << j << endl;
}
//Variables can be declared everywhere :
#include <iostream.h>
void main ()
{
double a;
cout << "Hello, this is a test program." << endl;
cout << "Type parameter a : ";
cin >> a;
a = (a + 1) / 2;
double c;
c = a * 5 + 1;
cout << "c contains : " << c << endl;
int i, j;
i = 0;
j = i + 1;
cout << "j contains : " << j << endl;
}
Input from keyboard and output to screen can be performed through cout and cin
//Input from keyboard and output to screen can be performed through cout and cin :
#include <iostream.h>
void main()
{
int a; // a is an integer variable
char s [100]; // s points to a string of 99 characters
cout << "This is a sample program." << endl;
cout << endl; // Line feed (end of line)
cout << "Type your age : ";
cin >> a;
cout << "Type your name : ";
cin >> s;
cout << endl;
cout << "Hello " << s << " you're " << a << " old." << endl;
cout << endl << endl << "Bye !" << endl;
}
//Input from keyboard and output to screen can be performed through cout and cin :
#include <iostream.h>
void main()
{
int a; // a is an integer variable
char s [100]; // s points to a string of 99 characters
cout << "This is a sample program." << endl;
cout << endl; // Line feed (end of line)
cout << "Type your age : ";
cin >> a;
cout << "Type your name : ";
cin >> s;
cout << endl;
cout << "Hello " << s << " you're " << a << " old." << endl;
cout << endl << endl << "Bye !" << endl;
}
programme for use of ,//,
//You can use / / to type a remark :
#include <iostream.h> // This library is often used
void main () // The program's main routine.
{
double a; // Declaration of variable a.
a = 456;
a = a + a * 21.5 / 100; // A calculation.
cout << a; // Display the content of a.
}
//You can use / / to type a remark :
#include <iostream.h> // This library is often used
void main () // The program's main routine.
{
double a; // Declaration of variable a.
a = 456;
a = a + a * 21.5 / 100; // A calculation.
cout << a; // Display the content of a.
}
a simple example of use of fputchar() function
#include <stdio.h>
int main(void)
{
char msg[] = "This is a test";
int i = 0;
while (msg[i])
{
fputchar(msg[i]);
i++;
}
return 0;
}
#include <stdio.h>
int main(void)
{
char msg[] = "This is a test";
int i = 0;
while (msg[i])
{
fputchar(msg[i]);
i++;
}
return 0;
}
programme to show use of ungetc()function i.e. to send something to buffer.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int i=0;
char ch;
puts("Input an integer followed by a char:");
/* read chars until non digit or EOF */
while((ch = getchar()) != EOF && isdigit(ch))
i = 10 * i + ch - 48; /* convert ASCII into int value */
/* if non digit char was read, push it back into input buffer */
if (ch != EOF)
ungetc(ch, stdin);
printf("i = %d, next char in buffer = %c\n", i, getchar());
return 0;
}
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int i=0;
char ch;
puts("Input an integer followed by a char:");
/* read chars until non digit or EOF */
while((ch = getchar()) != EOF && isdigit(ch))
i = 10 * i + ch - 48; /* convert ASCII into int value */
/* if non digit char was read, push it back into input buffer */
if (ch != EOF)
ungetc(ch, stdin);
printf("i = %d, next char in buffer = %c\n", i, getchar());
return 0;
}
programme for use of getche() function. i.e. to know the key just entered
#include <stdio.h>
#include <conio.h>
int main(void)
{
char ch;
printf("Input a character:");
ch = getche();
printf("\nYou input a key::' %c '\n", ch);
return 0;
}
#include <stdio.h>
#include <conio.h>
int main(void)
{
char ch;
printf("Input a character:");
ch = getche();
printf("\nYou input a key::' %c '\n", ch);
return 0;
}
programme to read from a file--e.g. of getw() and putw() functions
#include <stdio.h>
#include <stdlib.h>
#define FNAME "test.$$$"
int main(void)
{
FILE *fp;
int word;
/* place the word in a file */
fp = fopen(FNAME, "wb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
word = 94;
putw(word,fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);
/* clean up */
fclose(fp);
unlink(FNAME);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define FNAME "test.$$$"
int main(void)
{
FILE *fp;
int word;
/* place the word in a file */
fp = fopen(FNAME, "wb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
word = 94;
putw(word,fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);
/* clean up */
fclose(fp);
unlink(FNAME);
return 0;
}
programme to show use of vfprintf() and fscanf()
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
FILE *fp;
int vfpf(char *fmt, ...)
{
va_list argptr;
int cnt;
va_start(argptr, fmt);
cnt = vfprintf(fp, fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
fp = tmpfile();
if (fp == NULL)
{
perror("tmpfile() call");
exit(1);
}
vfpf("%d %f %s", inumber, fnumber, string);
rewind(fp);
fscanf(fp,"%d %f %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);
fclose(fp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
FILE *fp;
int vfpf(char *fmt, ...)
{
va_list argptr;
int cnt;
va_start(argptr, fmt);
cnt = vfprintf(fp, fmt, argptr);
va_end(argptr);
return(cnt);
}
int main(void)
{
int inumber = 30;
float fnumber = 90.0;
char string[4] = "abc";
fp = tmpfile();
if (fp == NULL)
{
perror("tmpfile() call");
exit(1);
}
vfpf("%d %f %s", inumber, fnumber, string);
rewind(fp);
fscanf(fp,"%d %f %s", &inumber, &fnumber, string);
printf("%d %f %s\n", inumber, fnumber, string);
fclose(fp);
return 0;
}
programme for use of getchar() function
#include <stdio.h>
int main(void)
{
int c;
/* Note that getchar reads from stdin and
is line buffered; this means it will
not return until you press ENTER. */
while ((c = getchar()) != '\n')
printf("%c", c);
return 0;
}
#include <stdio.h>
int main(void)
{
int c;
/* Note that getchar reads from stdin and
is line buffered; this means it will
not return until you press ENTER. */
while ((c = getchar()) != '\n')
printf("%c", c);
return 0;
}
output
int main()
{
char a[10]={'mayur'}
for(int i=0;i<=10;i++)
{
cout<<a[i];
cout<<"\n";
}
getch();
return 0;
}
int main()
{
char a[10]={'mayur'}
for(int i=0;i<=10;i++)
{
cout<<a[i];
cout<<"\n";
}
getch();
return 0;
}
palindrome
int main()
{
int n;
char a[20];
cout<<"enter how many digit string u want 2 enter";
cin>>n;
cout<<"enter the string";
cin>>a;
for(inti=0;i<=n;i++)
{
for(int j=n;j>=0;j--)
if (a[i]==a[j])
s=0;
else
s=1;
}
if(s==0)
cout<<"no.is palindrome ";
else
cout<<"no. is not palindrome";
getch()
return 0;
}
int main()
{
int n;
char a[20];
cout<<"enter how many digit string u want 2 enter";
cin>>n;
cout<<"enter the string";
cin>>a;
for(inti=0;i<=n;i++)
{
for(int j=n;j>=0;j--)
if (a[i]==a[j])
s=0;
else
s=1;
}
if(s==0)
cout<<"no.is palindrome ";
else
cout<<"no. is not palindrome";
getch()
return 0;
}
even no. program
int main()
{
int n;
cout<<"enter the number";
cin>>n;
if(n%2==0)
cout<<"number entered is even";
else
cout<<"number is not even";
getch();
return 0;
}
int main()
{
int n;
cout<<"enter the number";
cin>>n;
if(n%2==0)
cout<<"number entered is even";
else
cout<<"number is not even";
getch();
return 0;
}
initials
int main()
{
char a[20];
cout<<"enter ur name";
cin>>a
for(int i=1;i<=10;i++)
{
cout<<a;
}
getch();
}
int main()
{
char a[20];
cout<<"enter ur name";
cin>>a
for(int i=1;i<=10;i++)
{
cout<<a;
}
getch();
}
matrix
int main()
{
int a[3][3]={1,1,1,1,1,1,1,1,1};
int b[3][3]={2,2,2,2,2,2,2,2,2}
int c[3][3]={0,0,0,0,0,0,0,0,0};
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
c[i][j]=a[i][j]+ b[i][j];
cout<<c[i][j]<<"\t";
}
cout<<\n;
}
getch();
}
int main()
{
int a[3][3]={1,1,1,1,1,1,1,1,1};
int b[3][3]={2,2,2,2,2,2,2,2,2}
int c[3][3]={0,0,0,0,0,0,0,0,0};
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
c[i][j]=a[i][j]+ b[i][j];
cout<<c[i][j]<<"\t";
}
cout<<\n;
}
getch();
}
class
class m
{
public void show()
{
cout<<"my name is mayur";
}
};
int main()
{
m a;
a.show();
getch();
}
class m
{
public void show()
{
cout<<"my name is mayur";
}
};
int main()
{
m a;
a.show();
getch();
}
sequence
void main()
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
if (i==j)
{
printf("%d\n"i);
break ;
}
else
{
printf("%d",i);
continue ;
}
}
}
getch();
}
void main()
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
if (i==j)
{
printf("%d\n"i);
break ;
}
else
{
printf("%d",i);
continue ;
}
}
}
getch();
}
output
void main()
{
int i=1;
if(i==1)
printf("me");
else printf("u");
}
void main()
{
int i=1;
if(i==1)
printf("me");
else printf("u");
}
A puzzle
#include<graphics.h>
#include<dos.h>
#include<string.h>
#include<stdlib.h>
void drawgrid();
void shownumbers();
void initarr();
void startplay();
void movenumber();
void win_or_not();
int getkey();
int search();
char *a[] = {
" 1"," 4","15"," 7",
" 8","10"," 2","11",
"14"," 3"," 6","13",
"12"," 9"," 5"," "
};
char *arr[] = {
" 1"," 4","15"," 7",
" 8","10"," 2","11",
"14"," 3"," 6","13",
"12"," 9"," 5"," "
};
char *arr1[] = {
" 1"," 2"," 3"," 4",
" 5"," 6"," 7"," 8",
" 9","10","11","12",
"13","14","15"," "
};
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
drawgrid();
shownumbers();
startplay();
getch();
closegraph();
}
/* To draw the grid containing numbers */
void drawgrid()
{
int i,j,k;
setcolor(YELLOW);
rectangle(10,10,629,469);
setcolor(BLUE);
rectangle(219,139,419,339);
line(269,139,269,339);
line(319,139,319,339);
line(369,139,369,339);
line(219,189,419,189);
line(219,239,419,239);
line(219,289,419,289);
setcolor(CYAN);
settextstyle(7,0,1);
rectangle(20,20,170,80);
outtextxy(30,25,"ESC >> Exit");
outtextxy(30,55,"F1 >> Restart");
setcolor(RED);
settextstyle(1,0,3);
rectangle(230,50,400,80);
setcolor(YELLOW);
outtextxy(275,50,"PUZZLE");
}
/* To display numbers in the Grid */
void shownumbers()
{
int col,row,i,j,k;
i = 229;
j = 149;
k = 0;
setcolor(YELLOW);
settextstyle(2,0,7);
for(row=0;row<4;row++)
{
i = 229;
for(col=0;col<4;col++)
{
outtextxy(i,j,arr[k]);
i += 50;
k++;
}
j += 50;
}
}
/* To start playing the Game */
void startplay()
{
int key;
int solved;
while(1)
{
key = getkey();
movenumber(key);
win_or_not();
}/* end while */
}
/* Returns scancode of the key that has been hit */
int getkey()
{
union REGS i,o;
while(!kbhit())
;
i.h.ah = 0;
int86(22,&i,&o);
return(o.h.ah);
}
/* Retuens the index of blank string in the array arr[] */
int search()
{
int i,a;
for(i=0;i<16;i++)
{
a = strcmp(arr[i], " ");
if(a == 0)
break;
}
return(i);
}
/* Move a number to the blank position as per the arrow key being hit */
void movenumber(int key)
{
int blank;
int col,row,i,j,k;
char *temp;
switch(key)
{
/* for left key */
case 75: blank = search();
if(blank%4==3)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank+1];
arr[blank+1] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
/* for right key*/
case 77: blank = search();
if(blank%4==0)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank-1];
arr[blank-1] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
/* for up key */
case 72: blank = search();
if(blank>12)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank+4];
arr[blank+4] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
/* for down key */
case 80: blank = search();
if(blank<=3)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank-4];
arr[blank-4] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
case 1: exit(0);
case 59: cleardevice();
drawgrid();
initarr();
shownumbers();
break;
//startplay();
default: sound(1000);
delay(100);
nosound();
} /* end switch */
} /* function movenumber() ends here */
/* Check whether puzzle is solved or not */
void win_or_not()
{
int i,count=0;
int flag,k;
for(i=0;i<16;i++)
{
flag = strcmp(arr[i],arr1[i]);
if(flag==0)
count++;
} /* end for */
if(count==16)
{
setcolor(RED);
settextstyle(1,0,1);
outtextxy(55,380,"* * * * * Congratulations !! You solved the Puzzle * * * * *");
} /* end if */
} /* function win_or_not() ends here */
/* To initialize the array arr[] */
void initarr()
{
int k;
int count;
int count1;
randomize();
count = random(16);
count1 = random(16);
for(k=0;k<16;k++)
{
strcpy(arr[count],a[count1]);
count++;
count1++;
if(count>15)
count=0;
if(count1>15)
count1=0;
}
}
#include<graphics.h>
#include<dos.h>
#include<string.h>
#include<stdlib.h>
void drawgrid();
void shownumbers();
void initarr();
void startplay();
void movenumber();
void win_or_not();
int getkey();
int search();
char *a[] = {
" 1"," 4","15"," 7",
" 8","10"," 2","11",
"14"," 3"," 6","13",
"12"," 9"," 5"," "
};
char *arr[] = {
" 1"," 4","15"," 7",
" 8","10"," 2","11",
"14"," 3"," 6","13",
"12"," 9"," 5"," "
};
char *arr1[] = {
" 1"," 2"," 3"," 4",
" 5"," 6"," 7"," 8",
" 9","10","11","12",
"13","14","15"," "
};
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc\\bgi");
drawgrid();
shownumbers();
startplay();
getch();
closegraph();
}
/* To draw the grid containing numbers */
void drawgrid()
{
int i,j,k;
setcolor(YELLOW);
rectangle(10,10,629,469);
setcolor(BLUE);
rectangle(219,139,419,339);
line(269,139,269,339);
line(319,139,319,339);
line(369,139,369,339);
line(219,189,419,189);
line(219,239,419,239);
line(219,289,419,289);
setcolor(CYAN);
settextstyle(7,0,1);
rectangle(20,20,170,80);
outtextxy(30,25,"ESC >> Exit");
outtextxy(30,55,"F1 >> Restart");
setcolor(RED);
settextstyle(1,0,3);
rectangle(230,50,400,80);
setcolor(YELLOW);
outtextxy(275,50,"PUZZLE");
}
/* To display numbers in the Grid */
void shownumbers()
{
int col,row,i,j,k;
i = 229;
j = 149;
k = 0;
setcolor(YELLOW);
settextstyle(2,0,7);
for(row=0;row<4;row++)
{
i = 229;
for(col=0;col<4;col++)
{
outtextxy(i,j,arr[k]);
i += 50;
k++;
}
j += 50;
}
}
/* To start playing the Game */
void startplay()
{
int key;
int solved;
while(1)
{
key = getkey();
movenumber(key);
win_or_not();
}/* end while */
}
/* Returns scancode of the key that has been hit */
int getkey()
{
union REGS i,o;
while(!kbhit())
;
i.h.ah = 0;
int86(22,&i,&o);
return(o.h.ah);
}
/* Retuens the index of blank string in the array arr[] */
int search()
{
int i,a;
for(i=0;i<16;i++)
{
a = strcmp(arr[i], " ");
if(a == 0)
break;
}
return(i);
}
/* Move a number to the blank position as per the arrow key being hit */
void movenumber(int key)
{
int blank;
int col,row,i,j,k;
char *temp;
switch(key)
{
/* for left key */
case 75: blank = search();
if(blank%4==3)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank+1];
arr[blank+1] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
/* for right key*/
case 77: blank = search();
if(blank%4==0)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank-1];
arr[blank-1] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
/* for up key */
case 72: blank = search();
if(blank>12)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank+4];
arr[blank+4] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
/* for down key */
case 80: blank = search();
if(blank<=3)
{
sound(1000);
delay(100);
nosound();
break;
}
else
{
temp = arr[blank];
arr[blank] = arr[blank-4];
arr[blank-4] = temp;
cleardevice();
drawgrid();
shownumbers();
break;
}
case 1: exit(0);
case 59: cleardevice();
drawgrid();
initarr();
shownumbers();
break;
//startplay();
default: sound(1000);
delay(100);
nosound();
} /* end switch */
} /* function movenumber() ends here */
/* Check whether puzzle is solved or not */
void win_or_not()
{
int i,count=0;
int flag,k;
for(i=0;i<16;i++)
{
flag = strcmp(arr[i],arr1[i]);
if(flag==0)
count++;
} /* end for */
if(count==16)
{
setcolor(RED);
settextstyle(1,0,1);
outtextxy(55,380,"* * * * * Congratulations !! You solved the Puzzle * * * * *");
} /* end if */
} /* function win_or_not() ends here */
/* To initialize the array arr[] */
void initarr()
{
int k;
int count;
int count1;
randomize();
count = random(16);
count1 = random(16);
for(k=0;k<16;k++)
{
strcpy(arr[count],a[count1]);
count++;
count1++;
if(count>15)
count=0;
if(count1>15)
count1=0;
}
}
Rainbow colors
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<alloc.h>
#include<dos.h>
#define WAIT 5
int main()
{
int gd=DETECT,gm,maxx,maxy,x=0,y=0;
char ch;
int i,j,k=0;
int a,b,c,d,e,f,g,h,l,col=1;
initgraph(&gd,&gm,"");//Enter your BGI Directory
//Not Neccessary
/*c=250;
d=100;
e=390;
f=25;
g=530;
h=100;
a=110;
b=25;*/
x=45;
y=25;
l=1;
while(!kbhit())
{
//col++;
/*if(k==2)
{
c=250;
d=100;
e=390;
f=25;
g=530;
h=100;
a=110;
b=25;
} */
for(j=0;j<78;j++)
{
/* setcolor(l);
circle(c,d,2);
d+=1;
setcolor(l+2);
circle(g,h,2);
h+=1;
setcolor(l+3);
circle(e,f,25);
f+=1;
setcolor(l+5);
circle(a,b,25);
b+=1; */
setcolor(col);
circle(x,y,25);
y+=6;
delay(WAIT);
if(y>430)
{
break;
}
}
if(k==4)
{
while(1)
{
col++;
for(j=0;j<67;j++)
{
setcolor(col);
circle(x,y,25);
x-=2;
y-=6;
delay(WAIT);
}
//col+=2;
for(j=0;j<67;j++)
{
setcolor(k);
circle(x,y,25);
y+=6;
delay(WAIT);
}
col++;
k++;
if(k==8)
{
col++;
k=0;
break;
//exit(0);
}
}
x=45;
y=437;
//break;
/*getch();
closegraph();
restorecrtmode();
exit(0);*/
}
l++;
col++;
for(j=0;j<67;j++)
{
/* setcolor(l);
circle(c,d,25);
d+=1;
setcolor(l+1);
circle(g,h,25);
h+=1;
setcolor(l+3);
circle(e,f,2);
f+=1;
setcolor(l+2);
circle(a,b,2);
b+=1; */
x+=2;
setcolor(col);
y-=6;
circle(x,y,25);
delay(WAIT);
}
col++;
l++;
k++;
y=25;
}
return(0);
//exit(0);
}
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<alloc.h>
#include<dos.h>
#define WAIT 5
int main()
{
int gd=DETECT,gm,maxx,maxy,x=0,y=0;
char ch;
int i,j,k=0;
int a,b,c,d,e,f,g,h,l,col=1;
initgraph(&gd,&gm,"");//Enter your BGI Directory
//Not Neccessary
/*c=250;
d=100;
e=390;
f=25;
g=530;
h=100;
a=110;
b=25;*/
x=45;
y=25;
l=1;
while(!kbhit())
{
//col++;
/*if(k==2)
{
c=250;
d=100;
e=390;
f=25;
g=530;
h=100;
a=110;
b=25;
} */
for(j=0;j<78;j++)
{
/* setcolor(l);
circle(c,d,2);
d+=1;
setcolor(l+2);
circle(g,h,2);
h+=1;
setcolor(l+3);
circle(e,f,25);
f+=1;
setcolor(l+5);
circle(a,b,25);
b+=1; */
setcolor(col);
circle(x,y,25);
y+=6;
delay(WAIT);
if(y>430)
{
break;
}
}
if(k==4)
{
while(1)
{
col++;
for(j=0;j<67;j++)
{
setcolor(col);
circle(x,y,25);
x-=2;
y-=6;
delay(WAIT);
}
//col+=2;
for(j=0;j<67;j++)
{
setcolor(k);
circle(x,y,25);
y+=6;
delay(WAIT);
}
col++;
k++;
if(k==8)
{
col++;
k=0;
break;
//exit(0);
}
}
x=45;
y=437;
//break;
/*getch();
closegraph();
restorecrtmode();
exit(0);*/
}
l++;
col++;
for(j=0;j<67;j++)
{
/* setcolor(l);
circle(c,d,25);
d+=1;
setcolor(l+1);
circle(g,h,25);
h+=1;
setcolor(l+3);
circle(e,f,2);
f+=1;
setcolor(l+2);
circle(a,b,2);
b+=1; */
x+=2;
setcolor(col);
y-=6;
circle(x,y,25);
delay(WAIT);
}
col++;
l++;
k++;
y=25;
}
return(0);
//exit(0);
}
programme to enter a string using gets function
#include <stdio.h>
int main(void)
{
char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
return 0;
}
#include <stdio.h>
int main(void)
{
char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
return 0;
}
programme to show the use of puts function
#include <stdio.h>
int main(void)
{
char string[] = "This is an example output string\n";
puts(string);
return 0;
}
#include <stdio.h>
int main(void)
{
char string[] = "This is an example output string\n";
puts(string);
return 0;
}
programme to write something on screen by c puts function and window function
#include <conio.h>
int main(void)
{
/* clear the screen */
clrscr();
/* create a text window */
window(10, 10, 80, 25);
/* output some text in the window */
cputs("This is within the window\r\n");
/* wait for a key */
getch();
return 0;
}
#include <conio.h>
int main(void)
{
/* clear the screen */
clrscr();
/* create a text window */
window(10, 10, 80, 25);
/* output some text in the window */
cputs("This is within the window\r\n");
/* wait for a key */
getch();
return 0;
}
programme to know the ~ operator
/*programme to know the ~ operator*/
#include<stdio.h>
void main()
{
int i=~0;
printf("%d,%d,%d",i,i++,++i);
}
/*programme to know the ~ operator*/
#include<stdio.h>
void main()
{
int i=~0;
printf("%d,%d,%d",i,i++,++i);
}
programme to show use of spawn command interrupter
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("About to spawn command interpreter and run a DOS command\n");
system("dir");
return 0;
}
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("About to spawn command interpreter and run a DOS command\n");
system("dir");
return 0;
}
programme to set the background colour of output screen
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* select a driver and mode that supports */
/* multiple background colors. */
int gdriver = EGA, gmode = EGAHI, errorcode;
int bkcol, maxcolor, x, y;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* maximum color index supported */
maxcolor = getmaxcolor();
/* for centering text messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
x = getmaxx() / 2;
y = getmaxy() / 2;
/* loop through the available colors */
for (bkcol=0; bkcol<=maxcolor; bkcol++)
{
/* clear the screen */
cleardevice();
/* select a new background color */
setbkcolor(bkcol);
/* output a messsage */
if (bkcol == WHITE)
setcolor(EGA_BLUE);
sprintf(msg, "Background color: %d", bkcol);
outtextxy(x, y, msg);
getch();
}
/* clean up */
closegraph();
return 0;
}
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* select a driver and mode that supports */
/* multiple background colors. */
int gdriver = EGA, gmode = EGAHI, errorcode;
int bkcol, maxcolor, x, y;
char msg[80];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
/* maximum color index supported */
maxcolor = getmaxcolor();
/* for centering text messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
x = getmaxx() / 2;
y = getmaxy() / 2;
/* loop through the available colors */
for (bkcol=0; bkcol<=maxcolor; bkcol++)
{
/* clear the screen */
cleardevice();
/* select a new background color */
setbkcolor(bkcol);
/* output a messsage */
if (bkcol == WHITE)
setcolor(EGA_BLUE);
sprintf(msg, "Background color: %d", bkcol);
outtextxy(x, y, msg);
getch();
}
/* clean up */
closegraph();
return 0;
}
programme to get the current background colour
#include <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int bkcolor, midx, midy;
char bkname[35];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
/* for centering text on the display */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* get the current background color */
bkcolor = getbkcolor();
/* convert color value into a string */
itoa(bkcolor, bkname, 10);
strcat(bkname, " is the current background color.");
/* display a message */
outtextxy(midx, midy, bkname);
/* clean up */
getch();
closegraph();
return 0;
}
#include <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int bkcolor, midx, midy;
char bkname[35];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
/* for centering text on the display */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* get the current background color */
bkcolor = getbkcolor();
/* convert color value into a string */
itoa(bkcolor, bkname, 10);
strcat(bkname, " is the current background color.");
/* display a message */
outtextxy(midx, midy, bkname);
/* clean up */
getch();
closegraph();
return 0;
}
programme to draw and then fill the polygon
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
/* our polygon array */
int poly[10];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
maxx = getmaxx();
maxy = getmaxy();
poly[0] = 20; /* 1st vertext */
poly[1] = maxy / 2;
poly[2] = maxx - 20; /* 2nd */
poly[3] = 20;
poly[4] = maxx - 50; /* 3rd */
poly[5] = maxy - 20;
poly[6] = maxx / 2; /* 4th */
poly[7] = maxy / 2;
/*
drawpoly doesn't automatically close
the polygon, so we close it.
*/
poly[8] = poly[0];
poly[9] = poly[1];
/* draw the polygon */
drawpoly(5, poly);
/* clean up */
getch();
closegraph();
return 0;
}
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
/* our polygon array */
int poly[10];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
maxx = getmaxx();
maxy = getmaxy();
poly[0] = 20; /* 1st vertext */
poly[1] = maxy / 2;
poly[2] = maxx - 20; /* 2nd */
poly[3] = 20;
poly[4] = maxx - 50; /* 3rd */
poly[5] = maxy - 20;
poly[6] = maxx / 2; /* 4th */
poly[7] = maxy / 2;
/*
drawpoly doesn't automatically close
the polygon, so we close it.
*/
poly[8] = poly[0];
poly[9] = poly[1];
/* draw the polygon */
drawpoly(5, poly);
/* clean up */
getch();
closegraph();
return 0;
}
programme to draw a polygon
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
/* our polygon array */
int poly[10];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
maxx = getmaxx();
maxy = getmaxy();
poly[0] = 20; /* 1st vertext */
poly[1] = maxy / 2;
poly[2] = maxx - 20; /* 2nd */
poly[3] = 20;
poly[4] = maxx - 50; /* 3rd */
poly[5] = maxy - 20;
poly[6] = maxx / 2; /* 4th */
poly[7] = maxy / 2;
/*
drawpoly doesn't automatically close
the polygon, so we close it.
*/
poly[8] = poly[0];
poly[9] = poly[1];
/* draw the polygon */
drawpoly(5, poly);
/* clean up */
getch();
closegraph();
return 0;
}
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
/* our polygon array */
int poly[10];
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
/* terminate with an error code */
exit(1);
}
maxx = getmaxx();
maxy = getmaxy();
poly[0] = 20; /* 1st vertext */
poly[1] = maxy / 2;
poly[2] = maxx - 20; /* 2nd */
poly[3] = 20;
poly[4] = maxx - 50; /* 3rd */
poly[5] = maxy - 20;
poly[6] = maxx / 2; /* 4th */
poly[7] = maxy / 2;
/*
drawpoly doesn't automatically close
the polygon, so we close it.
*/
poly[8] = poly[0];
poly[9] = poly[1];
/* draw the polygon */
drawpoly(5, poly);
/* clean up */
getch();
closegraph();
return 0;
}
programme to draw an ellipse
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
int stangle = 0, endangle = 360;
int xradius = 100, yradius = 50;
/* initialize graphics, local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
/* terminate with an error code */
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
/* draw ellipse */
ellipse(midx, midy, stangle, endangle,
xradius, yradius);
/* clean up */
getch();
closegraph();
return 0;
}
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
int stangle = 0, endangle = 360;
int xradius = 100, yradius = 50;
/* initialize graphics, local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk)
/* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
/* terminate with an error code */
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
/* draw ellipse */
ellipse(midx, midy, stangle, endangle,
xradius, yradius);
/* clean up */
getch();
closegraph();
return 0;
}
programme for flushing last file
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
fflush out last entered datatype using fflush function
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
programme to show function of exit function
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
int main(void)
{
int status;
printf("Enter either 1 or 2\n");
status = getch();
/* Sets DOS errorlevel */
exit(status - '0');
/* Note: this line is never reached */
return 0;
}
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
int main(void)
{
int status;
printf("Enter either 1 or 2\n");
status = getch();
/* Sets DOS errorlevel */
exit(status - '0');
/* Note: this line is never reached */
return 0;
}
programme to clear the last graphical output screen
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
/* for centering screen messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* output a message to the screen */
outtextxy(midx, midy, "press any key to clear the screen:");
/* wait for a key */
getch();
/* clear the screen */
cleardevice();
/* output another message */
outtextxy(midx, midy, "press any key to quit:");
/* clean up */
getch();
closegraph();
return 0;
}
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
/* for centering screen messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);
/* output a message to the screen */
outtextxy(midx, midy, "press any key to clear the screen:");
/* wait for a key */
getch();
/* clear the screen */
cleardevice();
/* output another message */
outtextxy(midx, midy, "press any key to quit:");
/* clean up */
getch();
closegraph();
return 0;
}
programme to output a string with putc function
#include <stdio.h>
int main(void)
{
char msg[] = "Hello world\n";
int i = 0;
while (msg[i])
putc(msg[i++], stdout);
return 0;
}
#include <stdio.h>
int main(void)
{
char msg[] = "Hello world\n";
int i = 0;
while (msg[i])
putc(msg[i++], stdout);
return 0;
}
to print a charcter on output-screen using getc () function
#include <stdio.h>
int main(void)
{
char ch;
printf("Input a character:");
/* read a character from the
standard input stream */
ch = getc(stdin);
printf("The character input was: '%c'\n", ch);
return 0;
}
#include <stdio.h>
int main(void)
{
char ch;
printf("Input a character:");
/* read a character from the
standard input stream */
ch = getc(stdin);
printf("The character input was: '%c'\n", ch);
return 0;
}
programme to make a sub-string
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Borland International", *str2 = "nation", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", ptr);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Borland International", *str2 = "nation", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", ptr);
return 0;
}
programme to reverse a string
#include <string.h>
#include <stdio.h>
int main(void)
{
char *forward = "string";
printf("Before strrev(): %s\n", forward);
strrev(forward);
printf("After strrev(): %s\n", forward);
return 0;
}
#include <string.h>
#include <stdio.h>
int main(void)
{
char *forward = "string";
printf("Before strrev(): %s\n", forward);
strrev(forward);
printf("After strrev(): %s\n", forward);
return 0;
}
to convert a string of upper case to lower case
#include <stdio.h>
#include <string.h>
int main(void)
{
char *string = "Borland International";
printf("string prior to strlwr: %s\n", string);
strlwr(string);
printf("string after strlwr: %s\n", string);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char *string = "Borland International";
printf("string prior to strlwr: %s\n", string);
strlwr(string);
printf("string after strlwr: %s\n", string);
return 0;
}
how to compare two compare 2 strings
#include <string.h>
#include <stdio.h>
int main(void)
{
char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
int ptr;
ptr = strcmp(buf2, buf1);
if (ptr > 0)
printf("buffer 2 is greater than buffer 1\n");
else
printf("buffer 2 is less than buffer 1\n");
ptr = strcmp(buf2, buf3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 3\n");
else
printf("buffer 2 is less than buffer 3\n");
return 0;
}
#include <string.h>
#include <stdio.h>
int main(void)
{
char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
int ptr;
ptr = strcmp(buf2, buf1);
if (ptr > 0)
printf("buffer 2 is greater than buffer 1\n");
else
printf("buffer 2 is less than buffer 1\n");
ptr = strcmp(buf2, buf3);
if (ptr > 0)
printf("buffer 2 is greater than buffer 3\n");
else
printf("buffer 2 is less than buffer 3\n");
return 0;
}
copy elements of 1 string to other
#include <stdio.h>
#include <string.h>
int main(void)
{
char string[10];
char *str1 = "abcdefghi";
strncpy(string, str1, 3);
string[3] = '\0';
printf("%s\n", string);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char string[10];
char *str1 = "abcdefghi";
strncpy(string, str1, 3);
string[3] = '\0';
printf("%s\n", string);
return 0;
}
0 comments:
Post a Comment