Better
algorithm for multiplication
#include
#include
int fastmult (int x, int y)
{
int result;
result = 0;
while (y != 0)
{
if (y % 2 == 0)
{
x = 2*x;
y = y/2;
}
else
{
result = result + x;
y = y-1;
}
}
return(result);
}
int main ()
{
int x, y;
cout << "Enter two natural numbers: ";
cin >> x >> y;
cout << x << " * " << y << " = " << fastmult(x,y) << endl;
return(0);
}
Count
number of characters and lines in a file
#include
#include
#include
int main ()
{
ifstream f1;
char c;
int numchars, numlines;
f1.open("test");
numchars = 0;
numlines = 0;
f1.get(c);
while (f1)
{
while (f1 && c != '\n')
{
numchars = numchars + 1;
f1.get(c);
}
numlines = numlines + 1;
f1.get(c);
}
cout << "The file has " << numlines << " lines and "
<< numchars << " characters" << endl;
return(0);
}
Merge sort
#include
#include
#include
#include
int main ()
{
ifstream f1, f2;
ofstream f3;
int i,j;
f1.open("n1");
f2.open("n2");
f3.open("n1n2");
f1 >> i;
f2 >> j;
while (f1 && f2)
{
if (i < j)
{
while (i < j && f1 && f3)
{
f3 << i << endl;
f1 >> i;
}
}
else
{
while (j <= i && f2 && f3)
{
f3 << j << endl;
f2 >> j;
}
}
}
while (f1)
{
f3 << i << endl;
f1 >> i;
}
while (f2)
{
f3 << j << endl;
f2 >> j;
}
return (0);
}
No comments:
Post a Comment