If you like my posts please leave a comment.

Saturday, September 22, 2012

User Defined Functions in C++


Functions whose definitions are defined by the user(s) are known as user defined functions. In the practical world of solving an application problem which needs to be programmed, it is very hard to sit at one time and to write down the solution to the whole problem completely. Instead, it is better to think how we can fragment the whole complete problem into smaller sub parts and then how to solve those sub parts individually one after another then we can think on, how to unite all of those individual objects together into to form a single unit in-order to accomplish the goal.

Thursday, September 20, 2012

Some more programs using C++ Library Functions:



//program demonstrating the use of the functions - atoi(), atol(), itoa(), ltoa()
#include <iostream.h>
#include <stdlib.h>
int main()
{
int val1;//variable t store an integer value
long int val2;//variable to store a long integer value
int num1=12345;
long int num2=123456789;
char *str1="12345.33";
char *str2="23456789";
char string[30],string2[30];
val1=atoi(str1)+150;//adding 150 after converting the string to integer
val2=atol(str2)+1500;//adding 1500 after converting the string to long integer
itoa(num1,string,10);//converting an integer to string
ltoa(num2,string2,10);//converting an long int to string
cout<<"\n String was = "<<str1<<" and the new integer = "<<val1<<endl;
cout<<"\n String was = "<<str2<<" and the new long integer = "<<val2<<endl;
cout<<"\n Integer was = "<<num1<<" and the new string = "<<string<<endl;
cout<<"\n Integer was = "<<num2<<" and the new string = "<<string2<<endl;
return 0;
}
Output:



/*program to print the entered name in title case: This program is using strlen(), toupper(), tolower() functions*/
#include <iostream.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
char fname[30];char lname[30];
int flength,llength;
char temp;

cout<<"\n Enter Your First Name: ";
cin>>fname;
fflush(stdin);
cout<<"\n Enter Your Second Name: ";
cin>>lname;
flength=strlen(fname);
llength=strlen(lname);
     for(int i=0;i<flength;++i)
   {
      if(i<flength)
      {
     if(i == 0)
     {
     temp=fname[i];
      fname[i]=toupper(temp);
      }
      else
      fname[i]=tolower(fname[i]);
   }
   for(int i=0;i<llength;++i)
   {

      if(i == 0)

       lname[i]=toupper(lname[i]);
       else
       lname[i]=tolower(lname[i]);

   }


}
strcat(fname," ");
strcat(fname,lname);
cout<<"\nHello! "<<fname;
getch();
return 0;
}
Output:

/*Program to count total number of alphabets, digits, spaces, other characters present in a line of text entered. This program is using isalpha(), isdigit(), isspace() functions */
#include <iostream.h>
#include <ctype.h>
#include<conio.h>
int main()
{
char line[100];
clrscr();
int alpha=0,digi=0,spc=0,other=0,chars=0;
cout<<"\n Enter a line of text: ";
cin.getline(line,100);
     for(int i=0;line[i]!=NULL;++i)
   {
     if(isalpha(line[i]))
      alpha++;
      else if(isdigit(line[i]))
      digi++;
      else if(isspace(line[i]))
      spc++;
      else
      other++;
   }
   chars = alpha+digi+spc+other;
cout<<"\n Total Alphabets Present = "<<alpha;
cout<<"\n Total Digits Present = "<<digi;
cout<<"\n Total Spaces Present = "<<spc;
cout<<"\n Total Other characters Present = "<<other;
cout<<"\nTotal = "<<chars;
getch();
return 0;
}
Output:

Sunday, September 16, 2012

C++ FUNCTIONS TO GENERATE RANDOM NUMBERS



In C++ we can use some of miscellaneous and useful functions of stdlib.h to generate random numbers which are rand( ), srand( ),random( )and randomize( ).
            Simply to generate a random number, you can use rand( ) functions that produces a random number in the range 0 to RAND_MAX. The RAND_MAX is also defined in stdlib.h which gives you the maximum value returned by rand( ). For example if you execute this code given below it will generate 5 random numbers.
#include <iostream.h>
#include <stdlib.h>
int main()
{
int num,i;
     for(i=0;i<5;++i)
     {
          num=rand();
          cout<<num<<endl;
     }
}
Output:
Now if you run this same program you will notice same random numbers this program is generating.
2nd Run – 
3rd Run – 
4th Run – 

So, in order to generate a random number when ever you run the program you need to use srand( ) function in the above program. The srand( ) function starts generating a number from a point that depends on the value we pass to srand( ) as argument. Therefore, to generate a different number every time this function is executed we need seed (start) the function with a truly variable value such as system time. Now we can change the above code as follows:
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
# include <time.h> //to get system time through time_t
int main()
{
int num,i;
unsigned int sval;
time_t t;//t is a time type variable
sval=(unsigned)time(&t);
srand(sval);
     for(i=0;i<5;++i)
     {
          num=rand();
          cout<<num<<' ';
     }
getch();
}
Output:
1st Run -
2nd Run –
3rd Run –
Note** Remember one thing: srand( ) function should be used just once before the loop starts.

Generating a random number with a specified range:

The rand( ) function by default generates a number in range 0 to RAND_MAX. Now if you want to generate a number with our own specified range say – 5 to 14, then you can change the rand( ) as below:
(rand( ) % U) + L

(rand( ) % 10) + 5
Here your L = 5 and U = 10

random( ) and rnadomize( ):

in order to generate in users’ specified range we can use two more macros, also defined in stdlib.h they are random( ) and randomize( ). These two also having similar function as that of rand( ) and srand( ).
To generate a random number between 0 – 9 you can write:
random(10);
Output can be any one of these:
0          1          2          3          4          5          6          7          8          9
Because random( ) function generates a random number maximum up to n – 1.
So, to generate a random number between L – U (where L is your lower limit and U is your upper limit)
You should write:
 random(U – L + 1) + L
Example: random(100 – 50 + 1) + 50 (It will generate a number within the range 50 – 100)
Note** randomize ( ) function internally implements a macro that calls time function of time.h. So, you need to use time.h header file in your program to implement random ( ) function.
Example 1:
//Program to generate 5 random numbers in the range 5 - 14
//program is using srand( ) and rand( ) functions.
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
# include <time.h>
int main()
{
int num,i;
unsigned int sval;
time_t t;
sval=(unsigned)time(&t);
srand(sval);
     for(i=0;i<5;++i)
     {
          num=(rand()%10) + 5;
          cout<<num<<' ';
     }
getch();
}Output:
1st Run
2nd Run
3rd Run
4th Run

Example 2:
//Program to generate 5 random numbers in the range 5 - 14
//program is using randomize( ) and random( ) functions.
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
# include <time.h>
int main()
{
int num,i;
randomize();
     for(i=0;i<5;++i)
     {
          num=random(14-5+1)+5;
          cout<<num<<' ';
     }
getch();
}
Output:
1st Run
2nd Run
3rd Run
4th Run


Note** For official explanation of any inbuilt library function or keyword you can always refer to the HELP menu of TurboC++ 3.0 IDE. The main reason behind writing all these contents only is to explain the topics in best possible way using examples and other ways of illustration. That's why wherever it is possible I have added snapshots of screen outputs or snaps of program code with graphical illustrations. Please refer to all those resources. 

Sunday, September 9, 2012

MATHEMATICAL FUNCTIONS


C++ provides various mathematical functions, which can be used as an aid to mathematical calculations in your program. To use these mathematical factions you need to include math.h header file in your program. Table given below summarizes some of the important mathematical functions used in C++.
Function
Description
Example
int abs(int x)
abs() function returns the absolute value of the integer argument x. If abs is called when stdlib.h has been included, it's treated as a macro that expands to inline code. If you want to use the abs function instead of the macro, include #undef abs
in your program, after the #include <stdlib.h>.
int number = -1234;
cout<<"\n Absolute value of "<<number<<" = "<<abs(number);
Output:
double fabs(double x)
Returns the absolute value of a floating-point number. fabs calculates the absolute value of x, a double.
float  number = -1234.05;
cout<<"number:"<<number<<" Absolute value: "<<fabs(number);
Output:
double fmod(double x, double y)
fmod() function, calculates x modulo y, the remainder of x/y.
fmod calculates x modulo y (the remainder f, where x = ay + f for some integer a, and 0 < f < y).
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
#include <conio.h>

int main(void)
{
   double x = 5.0, y = 2.0;
   double result;

   result = fmod(x,y);
   cout.setf(ios::showpoint);
   cout<<"The remainder of "<<setprecision(2)<<x<<" / "<<y<<" = "<<result;
getch();
   return 0;
}
Output:
double modf(double x, double *ipart)
modf() function, breaks the double x into two parts: the integer and the fraction. modf stores the integer in ipart and returns the fraction.
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
#include <conio.h>
int main(void)
{
   double fraction, integer;
    double number = 100000.567;

    fraction = modf(number, &integer);
    cout.setf(ios::fixed);
    cout<<"The whole and fractional parts of"<<setprecision(3)<<number<<" are "<<", "<<integer<<" and "<<fraction;
   getch();
   return 0;
}
Output:
double log(double x)
log() function calculates the natural logarithm of x.
int main(void)
{
   double result;
   double x = 8.6872;

   result = log(x);
   cout<<"The natural log of "<<x<<" = "<<result;
   getch();
   return 0;
}
Output:
double pow(double x, double y)
pow() function, calculates x to the power of y. If the argument x passed to pow is real and less than 0, and y is not a whole number, or you call pow(0,0), the global variable errno is set to
EDOM               Domain error
double x = 2.0, y = 3.0;
cout<<x<<" is raised to "<<y<<" = "<<pow(x, y);
 Output:
double sqrt(double x);
sqrt() function, calculates the positive square root of the argument x. On success, sqrt return the value calculated, the square root of x. If x is real and positive, the result is positive. If x is real and negative, the global variable errno is set to
EDOM               Domain error
double x = 4.0, result;
result = sqrt(x);
cout.setf(ios::fixed);
cout<<"\n The Square root of "<<setprecision(1)<<x<<" = "<<result;
Output:
double sin(double x)
sin() function computes the sine of the input value. Angles are specified in radians.
double result, x = 0.5;
result = sin(x);
cout.setf(ios::fixed);
cout<<"\n The sin of "<<setprecision(2)<<x<<" = "<<result;
Output:
double cos(double x)
cos() function calculates the cosine of the input value. The angle is specified in radians.
double result, x = 0.5;
result = cos(x);
cout.setf(ios::fixed);
cout<<"\n The cosine of "<<setprecision(2)<<x<<" = "<<result;
Output:
double ceil(double x)
Rounds up
ceil() finds the smallest integer not less than x.
double number = 123.54;
double up,down;
    up = ceil(number);
    down = floor(number);
    cout<<"\n The original number: "<<number;
    cout<<"\n number rounded up to: "<<up;
    cout<<"\n number rounded down to: "<<down;
Output:
double floor(double x)
Rounds down.
floor() finds the largest integer not greater than x.
double poly(double x, int degree, double coeffs[])
poly() function generates a polynomial in x, of degree degree, with coefficients coeffs[0], coeffs[1], ..., coeffs[degree]. For Example if x = 3, the generated polynomial is : coffes[3]x3 + coffes[2]x2 + coffes[1]x1 + coffes[0]x0
poly() returns the value of the polynomial as evaluated for the given x.
#include <iostream.h>
 #include <conio.h>
 #include <math.h>
//polynomial:  x**3 - 2x**2 + 5x - 1
int main(void)
{
  double array[] = { -1.0, 5.0, -2.0, 1.0};
  double result;

  result = poly(2.0, 3, array);
  cout<<"\nThe polynomial: x**3 - 2.0x**2 + 5x - 1 at 2.0 = "<<result;
  getch();
  return 0;
}
Output:

STRING AND CHARACTER RELATED FUNCTIONS


In C++ string is a null-terminated array of characters. To manipulate strings in C++ we need the help of string functions and this requires including the header file string.h in order to include function prototype and definition. To manipulate characters we need to use character functions and this requires including ctype.h header file in your program.

Character Functions:

Here by below I am including some of the important character functions with descriptions:
Function
Description
Example
int isalnum(int ch)
The function isalnum() returns non-zero if its argument is a letter or a digit. If the character is not an alphanumeric isalnum() returns 0 (Zero)
char ch;
if(isalnum(ch))
cout<<”\n Alphanumeric”;
else
cout<<”\n Non-Alphanumeric”;
int isalpha(int ch)
The function isalpha() returns non-zero if ch is a alphabet, else returns zero.
char ch;
if(isalpha(ch))
cout<<”\n An alphabet”;
else
cout<<”\n No an alphabet”;
int isdigit(int ch)
This functions returns non-zero if ch is a digit (0 – 9) else returns zero.
char ch;
if(isalpha(ch))
cout<<”\n Is a digit”;
else
cout<<”\n Not a digit”;
int isxdigit(int ch)
Tests for hexadecimal character.
isxdigit is a macro that classifies ASCII-coded integer values by table lookup. You can make this macro available as a function by un-defining (#undef) it.
int main(void)
{
  char ch = 'F';
  if (isxdigit(ch))
    cout<<ch<<" is a hexidecimal digit";
  else cout<<ch<<"\n is not a hexidecimal digit";
   getch();
  return 0;
}
Output:
int isupper(int ch)
Function isupper() returns non-zero if ch is in upper case; else returns zero.
char ch;
if(isupper(ch))
cout<<”\n Is in upper case”;
else
cout<<”\n is in lower case”;
int islower(int ch)
Function islower() returns non-zero if ch is in lower case; else returns zero.
char ch;
if(islower(ch))
cout<<”\n Is in lower case”;
else
cout<<”\n is in upper case”;
int isspace(int c)
isspace is a macro that classifies ASCII-coded integer values by table lookup
char ch = ' ';
if (isspace(ch))
cout<<ch<<"is a white space";
else cout<<ch<<"is not white space\n";
Output:
 is a white space
int toupper(int ch)
Function toupper(), return upper case equivalent to ch; otherwise keeps the character unchanged.
char ch;
cout<<toupper(ch);
int tolower(int ch)
Function tolower(), returns lower case equivalent to ch; otherwise keeps the character unchanged.
char ch;
cout<<tolower(ch);
int toascii(int ch)
toascii is a macro that converts the integer c to ASCII by clearing all but the lower 7 bits; this gives a value in the range 0 to 127
char ch;int result;
ch ='^';
result = toascii(ch);
cout<<"\n ASCII of "<<ch<<" = "<<result;
Output:
ASCII of ^ = 94
 
Note** All above mentioned character function uses ASCII equivalent of the passed character to compare or to convert. That is why on all above functions passed argument is shown as of type int.
 

String Functions:

The table given below summarizes some of the important string functions used in C++. To use these functions you need to include string.h header file.

String Functions:

The table given below summarizes some of the important string functions used in C++. To use these functions you need to include string.h header file.
Function
Description
Example
char *strcat(char *str1, const char *str2)
The function strcat(), concatenates a copy of str2 to str1 and terminates str1 with a null character. Remember str1 should be large enough to hold both, its original content and the contents of str2.
char *str1="Computer";char *str2=" Science";
strcat(str1,str2);
cout<<str1<<endl;
Output:
Computer Science
int strcmp(const char *str1, const char *str2)
The function strcmp(), alphabetically compares two strings passed as arguments. It returns –ve value if str1 is less than str2; 0 if str1 and str2 are equal; and returns +ve value if str1 is greater than str2.
const char *str1="Abc";
const char *str2="Def";
cout<<strcmp(str1,str2)<<endl;
cout<<strcmp(str2,str1);
Output:
-3
3
char *strcpy(char *str1, const char *str2)
Function strcpy(), copies the content of str2 into str1.
char *str1=" ";
const char *str2="C++";
strcpy(str1,str2);
cout<<str1<<endl;
Output:
C++
int strlen(const char *str)
Function strlen(), returns the length of the null-terminated string pointed by str. The null character is not counted.
const char *str="C++";
cout<<strlen(str)<<endl;
output:
3
char *strrev(char *s)
Reverses a string.
strrev() function changes all characters in a string to reverse order, except the terminating null character
int main(void)
{
   char *mystr = "string";

   cout<<"Before strrev(): "<<mystr;
   strrev(mystr);
   cout<<"\nAfter strrev(): "<<mystr;
   getch();
   return 0;
}
Output:
char *strset(char *s, int ch)
Sets all characters in a string to a given character.
strset() function sets all characters in the string s to the character ch. It quits when the terminating null character is found.
int main(void)
{
   char string[10] = "123456789";
   char symbol = '*';

   cout<<"Before strset(): "<<string;
   strset(string, symbol);
   cout<<"\nAfter strset(): "<<string;

   getch();
   return 0;
}
Output: