Friday, 2 March 2012

C++ program that counts the number of words in a string or a line


This is a C++ program, with the help of which you can find out how many words are there in a string or a line. Below is the coding.

#include "iostream.h"
#include "conio.h"
#include "string.h"
main()
{
 char str[50];
 int i, count = 1;
 cout << "\n\t Enter the string ";
 gets(str);
 while((str[i]!= '\0') && (str[i+1] != ' '))
 {
  if ((str[i] == ' ') || (str[i] == '.'))
  count++;
  i++;
 }
 cout << "\n\t Number of words in a string is " << count;
 return 0;
}

Step by step explanation: 
1. Header files used are iostream.h for input and out put functions, conio.h is used for functions like getch() and clrscr(), and string.h is used for function gets() and other string related function. If you don't use any of the above header file. The possible error which may come is : "X function should have prototype", where X can be any function.
2. main() function is starting of every function. All working, calls and loops are defined under main function only.
3. gets() function can be treated as an alternative of cin, when the case comes for string.
If you find any difficulty in understanding the program, or you have any proble, you may post your comment below.

Thursday, 23 February 2012

Structures in C and C++ programming


Structure :
A structure is a meaningful collection of data items of different types under a unique name.
Declaration of a structure

Struct name
{
Type1 data1;
Type2 data2;
.
.
.
Typen datan;
};


Where
Struct is a keyword
Name  is name of structure
Type1,. . . typen  are basic data type.
Data1, . .. datan is data items or structure variables.

Example

Struct stud
{
Int name[20];
Int branch[20];
Int semester;
};


Like ordinary variables, we can  also define and declare structure variables. The general form of declaring structure variables is
Structure_type varlist;
Example: struct stud x, y;
This can be done with the structure declaration.

Example

Struct stud
{
Int name[20];
Char branch[20];
Int semester;
} x, y;




Processing of a structure


Processing of a structure is mainly concerned  with accessing a structure member. Each member of a structure is accessed with a dot operator, that is the decimal point.to access a particular member, this dot operator must placed between the name of structureand the name of the structure member.
For example:
Stud.name
The result of expression is name of the student of type struct stud.the dot operator has highest priority thanany other operator in c,and associativity is left to right.
Embedded structure declaration

A structure within another structure is called embedded structure.
Example:

Struct employee
{
Int emp_code;
Char name[20];
Float salary;
Struct date
{
Int day;
Int month;
Int year;
}date_of_birth;
};


Initialization of a structure


Structure can be initialized as
Static struct stud student=(“kumar”, “ computer science”,8};
This will store kumar in name array computer science In branch array and 8 in semester aray.

Array of  structure
Whenever the same structure is to be applied to a group of people, items, etc.., in such situation , an array of structures will be definrd. In array of structures  each element is array in itself.
Example:
Struct stud_rec
{
Int rollno;
Char name[3];
Int m1;
Int m2;
Float avg;
}stud_rec[30];


This code will create an array of this structure in which there is record of student is stored.
Type definition, typedef statement
All variables are declared withthere basic datatype  such as int , float, char etc. it is possible for the user to define his/her own datatype  for the variables being used in program.c provides typedef  statement that enables the program to define an alternate term to the basic dattype. Once the typedef is made, the earliar datatype , all variables, arrays, structures etc, can be declared with the new data type.
Syntax:

Typedef old_ data_ type new_ data_ type;
Example
Struct stud_rec
{
Int reg_no;
Char name[25];
Char branch[20];
Int semester;
};


Typedef struct stud_rec learner;
Thus, we can declare any structure of type struct student in terms of learner.
Learner s1;

String functions in C and C++ programming

,
String input\output function


Gets( )
It is used to read a set of alphanumeric character from stdin until a carriage return key is pressed and places a NULL in memory or returns.

Syntax

Gets(variable name);
Program:

#include<stdio.h>
Main()
{
Char  string[5];
Gets(string);
}


Puts( )
Puts( ) function used to send characters   as output that is to stdout from stored data until it run into the NULL when it sends a newline and returns.

Syntax

Puts(variable name);
Program:

#include<stdio.h>
Main()
{
Char string[5];
Gets(string);
Puts(string);
}


sscanf( )
This function is same as scanf function but the difference is that it read data stored in an array instead of  data entered by keyboard.

Syntax:

Sscanf(memory name, “control characters”, variable name);


Program:

#include,stdio.h>
Main()
{
Char string[5];
Int I,j;
Float a,b;
Gets(string);
Sscanf(string, “%d%d%f%f\n”, I, j, a, b);
}


Sprint( )
Like printf this function also use to enter data, but the difference is that sprint  write  formatted data in array istead of memory.

Syntax:

Sprint(memory name, “control character”, variable name);
Program:

#include<stdio.h.
Main()
{
Char string[5];
Int I,j;
Float a, b;
Gets(char);
Sprint(string, “%d%d%f%f\n”, I , j, a, b);
}


String handling functions


Strcmp( )
This function compares two strings character by character and returns -1 if ASCII value of first string is less then second string, 0 if AsCII value of both string is same, and 1 if ASCII  value of first string is greater then second string.
Syntax:

Strcmp(string1, string2);


Strcpy( )
This function is used to copy one string to another.

Syntax:

Strcpy(string1, string2);


Example: strcpy(“mouse”,”keyboard”);
This copies the string keyboard to mouse. Here , the current content of mouse is lost.

Strcat( )
This function is used to concatenate two strings. That is it appends one string at the end of other string.
Syntax:

Strcat(string1, string2);

Example: (“computer”, “concepts”);

Output will be
 computer concepts.

Strlen( )

This returns the number of characters in string.
Syntax: strlen(string);
Example: strlen(“computer”);
Output will be:
8

Strcmp( )
This function compares the first n character of two input strings.
Syntax: (string1, string2, n);
Example: strcmp(“elephant”,” lion”, 4);
It compares starting 4 strings and output will be as that of strcmp()  dissed.

Strncpy( )
This copies first n characters of second string to the first string.
Syntax: strncpy(string1, string2, n);
Example: strncpy(“sachin”, “tendulkar”,6);
Output will be
Tendul
And sachin string will lost.

Strncat( )
This appends the first n character of second string to the end of first string,
Syntax: strncat(string1,string2);
example: strncat(“system”, “software engg”, 8);
output will be:
 system software

strlwr( )
this function converts string into lower case.
Syntax: strlwr(string);
Example: strlwr(“COMPUTER”);
Output will be
computer

strupr( )
it converts string into upper case.
Syntax: strupr(string1);
Example: strupr(“computer”);
Output will be:
COMPUTER

Strchr( ) 
This function search for the character provided in string.it returns NULL if the desired character is not found in the string.
Syntax: strchr(string, desired_char);
Example: strchr(“computer”, t);
Since t is in the string search is successful.

Header files in C and C++ programming


What are header files ?


Files that are placed at the header portion (before main()) of c program are called the header files.
Normally, the standard header files are having .h as extension which designates a header file. However , the user defined header files may have different extensions.
The header files are used to provide the necessary information in support of the various library functions. Each header file contains declaration for certain related library function. For example, stdio.h is a header file containing declarations for input/output functions. Similarly math.h header file contains declaration for certain mathematical functions.some of the important and commonly used header files are:

stdio.h                  input/output  functions
math.h                  mathematical functions
string.h                 string manipulation functions
malloc.h               memory allocation/deallocation function
stdlib.h                 some standard library function
ctype.h                character manipulation fuction
time.h                  time computing functions
graphics.h            graphical function
dos.h                   functions linking DOS routines.


The header files are entered into the source program via a #include statement. The # include statement is a preprocessor statement and must be written at the beginning of the program.
The stdio.h header file can be included in your source program by writing the following statement
#include<stdio.h>
Observe that the header file stdio.h is enclosed within angle brackets(< >). Alternatively, we can also write the header file within double quotes as

#include”stdio.h”


If we write the header file is enclosed within angle brackets, it means that the compiler will search for the header file in the default include directory. (Note that the include directory is one in whichthe compiler’s installation program  will place the header files).  If the required header file is not found in the current directory during the compillation process, then the compiler searches for it in the include directory. On the other hand,  if we write the header file name within double quotes, the compiler will search for that header file in the current directory only. If the file is not found , it will flag an error message.

Function overloading


Function overloading


When several function declarations for a single function name in the same scope, the name is said to be overloaded. C++ allowed functions to have the same name if it can distinguish them by their number and types of arguments.
Example:
Float  mult(int a, int b);
Float  mult(float x, float y);


In this case mult function have two arguments  but one mult function have int argumants and other have float arguments.
This is known as function overloading.
Function overloading is a function having several definations that are different in respect of number  of arguments passed or datatypes of  the arguments.


Need for function overloading


While using different function for different situation we need to decide upon which function should be executed . but using function overloading compiler automatically decides which function should executed. It will not only reducing the number of if else but also make the code execute faster as so many caoparisons are eliminated.
For example:

Char choice;
Cout<< “its hot or cold? (Y|N)”;
cin>> choice:
if(choice==’Y’)
Hot();
Else if(choice==’n’)
Cold();
Else
Cout<<”\nwrong choice\n”;
.
.
Declaration and definition


The key to function overloading  is a function’s argument list which is also known as the function signature.
If two functions are having same number and types of argument s in the same order , they are said to have the same signature even if they are using distinct variable names, it does not matter. For example:

Void square(int a);
Void square(flaot x);


For declaring a function overload there must same name but different signatures.
After declaring a function  definition of function is done separately.

Void square(int a)
{ cout<<”integer” <<a<<” square is “ <<a*a<<”\n”;}
And 
2) Void square(float x)
{ cout<<”float”<<x<<”square is” <<x*x<<”\n”;}


Calling overloaded function
Overloaded functions are called just like other functions. for example:
Square(14.54F);    it will calls the function number 2 discussed above
Sometimes there might be ambiguity between float and double values or say int or long.to avoid this ambiguity constant suffixes must be provided (F, L,U,UL etc) to distinguish between such values.
An ordinary floating constant(321.89)has the double type, while adding F suffix(321.89F)  makes it’s a float.

Polymorphism (Oop concepts)

Polymorphism:


Polymorphism is the key to the power of object oriented programming. It is so important that languages that don’t support polymorphism cannot advertise themselves as OO languages. Languages that support classes but not polymorphism are called object-based languages. Ada is such a languages.
Polymorphism is the concept that support the capability of an object of a class to behave differently in response to a message or action. For instance, ‘human’ is a subclass of ‘Mammal’. Similarly ‘Dog’, ‘Cat’ are also subclasses of ‘Mammal’. Mammals can see through day-light. So if a message ‘see through daylight’ is passed to all Mammals, they all will behave alike. Now if the message ‘see through darkness’ is passed to all the mammals, then human and dogs will not be able to view at night whereas cats will be able to see during night also. Here cats(mammals) can behave differently than other mammals in response to a message or action. This is polymorphism.
Take another example. If you give 5+7, it results in 12, the sum of 5 and 7. And if you give ‘A’ +   ‘BC’, it results into ‘ABC’, the concatenated strings. The same operation symbol ‘+’ is able to distinguish between two operations (summation and concatenation) depending upon the data type it is working on.
Polymorphism is a property by which the same message can be sent to objects of several different classes, and each object can respond in different way depending upon its class.

Implementation polymorphism


C++ implements polymorphism through virtual functions, through overloaded functions and overloaded operators. A virtual function is used to specify the interface is abstract class, but its implementation details are made available by concrete classes, the term overloading means a name having two or more distinct meanings. Thus an overload function refers to a function having more than one distinct meanings. Similarly when two or more  distict meanings are defined for an operator , it is said to be overload operator.
It is compiler job to select the specific action as it applies to each situation. In c++ polymorphism is implemented through overloading and virtual functions.

Saturday, 18 February 2012

Strings in C++, Strings theory and concepts in C++


String

: A string is a sequence of characte that is treated as a single data item.

->

Functions used in string:-


   1. scanf() : It is a input function can be used with "%s" format specification to read in a string of character.
                   Example:
                             char address[10]
                             scanf("%s", address);
   2. getchar(): Use of this function to read single character from the input and place them in to character array.
                   Example:
                             char ch;
                             ch = getchar();
      'getchar' function has no parameters.
 
   3. gets() : It is a library function available in the <stdio.h> header file2  is used to read character in to string from the keyboard.
            This is a simple function wiyh one  string parameter.
                         
                              gets(str)
                   Example:
                             char line [80];
                             gets (line);
                             printf("%s", line);
 
   4. printf() : Used this function with "%s" format to print string to the screen.
                 
                   Example:
                             printf("%s", name);

   5. putchar() : This function is ysed to write character to the screen. And can use this function repeatedly to output a string
                  of character stored in an array using a loop.
                   ->Function putchar requires one parameter.
                   Example:
                             char name[6] = "PARIS";
                             for (i=0; i<5; i++)
                                  putchar(name[i]);
 
   6. puts() : This function is used for printing string values is to use the function 'puts' declared in the header file
               <stdio.h>.
               This is a one parameter function.
                             puts(str);
 
                                           

String-Handling Functions:


   1. strcat() : This functon join two string together. It takes the following form:
                             strcat(string1 , string2);

   2. strcmp()  : The strcmp function compares two strings identified by the arguments and hae the value 0 if they
                  are equal.
                             strcmp(string1 , string2);

   3. strcpy() : The strcpy function works almost like a string-assignment operator i.e is used copy second string in to
                 first string. It take forms :
                           
                             strcpy(string1 , string2);

   4. strlen() : The strlen function is used for count(count length of string) and returns the number of character in a
                 string. It takes form:
                         
                             n = strlen(string);
                         where n is a integer variable , which recieve the value of the length of the string.
                 The counting ends at the first null chartacter.

Other String Function:


   1. strncpy : This function copies only the left-most n characters of the surce string to the terget string variable.
                This is the three-parameter function and is invoked as follows:
                             strncpy(s1, s2, 5);
 
   2. strncmp : A variation of the function strcmp is the strncmp. This function has three-parameters as like:
                             strncmp(s1, s2, n);
                this compares the left-most n character of s1 to s2 and returns.
                (a) 0 if they are equal;
                (b) negative number, if s1 substring is less then s2;
                (c) positive number, otherwise.

   3. strncat : This is another concatenation function tht takes three parameter as shown below:
                       
                             strncat(s1, s2, n);
                this call will concatenate the left-most n character of s2 to the end of s1.

   4. strstr :  It is a two parameter function that can be used to locate sub-string in a string. This takes the forms:
         
                             strstr (s1, s2);            
                             strstr (s1, "ABC");