Showing posts with label Function. Show all posts
Showing posts with label Function. Show all posts

Saturday, May 16, 2015

indexof function in C Language program


There is no predefined indexof function in C Language. We will define a function named indexof in C language which will show the position of a character in a string.

 There will be two different indexof functions, one will take the original string as first argument and a character as the second argument. The function will show the first occurrence index location of the character in the string. If the character is not found in the string, the function will return =1.


  The second one will take the original string as first argument and a character as the second argument and an index as the third argument. The function will show the first occurrence index location of the character in the string after the specified index (3rd argument). If the character is not found in the string, the function will return =1.

  PROGRAM 1:

#include< string.h>
#include< stdio.h>
int indexof(char *,char);
 void main()
 {
  char ch[100];
  char c;
  int i;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the character:");
  c=getche();
  i=indexof(ch,c);
  if(i< 0)<0 o:p="">
  printf("\nThe character %c is not present in string %s",c,ch);
  else
    printf("\nThe character %c is in index %d in string %s",c,i,ch);
  getch();
  }
int indexof(char *p,char c)
{
int i=0;
 while(*p!=NULL)
 {
 if(c==*p)
 break;
 p++;
 i++;
 }
 if(*p==NULL)
 return -1;
 else
 return i;
 }


PROGRAM 2


#include< string.h>
#include< stdio.h>
int indexof(char *,char,int);
 void main()
 {
  char ch[100];
  char c;
  int x,i;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the character:");
  c=getche();
  printf("\nEnter the location after which the character to search:");
 scanf("%d",&i);
  x=indexof(ch,c,i);
 if (x< 0)
   printf("\nThe character %c is not present in string %s after index %d",c,ch,i);
  else
    printf("\nThe character %c is in index %d after index %d in string %s",c,x,i,ch);
  getch();
  }
int indexof(char *p,char c,int x)
{
int i=0;
 while(*p!=NULL)
 {
 if(i > x && c==*p)
 break;
 p++;
 i++;
 }
 if(*p==NULL)
 return -1;
 else
 return i;

 }

Friday, May 15, 2015

substring function in C Language program


There is no predefined substring function in C Language. We will define a function named substring in C language which will extract a part of the string from the original string.

 There will be two different substring functions, one will take the original string as first argument and an index of the string as the second argument. A part of the string from the location specified by the index value of the string upto the end of the string will be extracted.

  The second substring function will take the original string as first argument, an index of the string as the second argument and number of characters as the third argument. The function will extract a substring from the original string of specified characters (3rd argument) starting from the starting index (2nd argument).


  PROGRAM 1:

#include< string.h>
#include< stdio.h>
char * substring(char *,int);
 void main()
 {
  char ch[100];
  int i;
  char *ptr;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the start index:");
  scanf("%d",&i);
 ptr=substring(ch,i);
  printf("\nSubstring=%s",ptr);
  getch();
  }
char *substring(char *p,int i)
{
 char str[100];
 int x=0,c=0;
 while(*p!=NULL)
 {
 if(c>=i)
 str[x++]=*p;
 p++;
 c++;
 }
 str[x]=NULL;
 return str;
 }

 PROGRAM 2


#include< string.h>
#include< stdio.h>
char * substring(char *,int,int);
 void main()
 {
  char ch[100];
  int i,j;
  char *ptr;
  clrscr();
  printf("\nEnter any string:");
  gets(ch);
  printf("\nEnter the start index:");
  scanf("%d",&i);
  printf("\nEnter the number of characters to extract:");
  scanf("%d",&j);

 ptr=substring(ch,i,j);
  printf("\nSubstring=%s",ptr);
  getch();
  }
char *substring(char *p,int i,int j)
{
 char str[100];
 int x=0,c=0;
 while(*p!=NULL)
 {
 if(c>=i && c str[x++]=*p)
 p++;
 c++;
 }
 str[x]=NULL;
 return str;
 }


Friday, February 1, 2013

Function overloading in BlueJ




Function overloading is an interesting feature of object oriented programming. Function overloading is one type of polymorphism. We can define number of functions with same name but the argument list of the functions must be different. The return type of overloaded functions may be same or different. The body statements of the overloaded functions will be definitely different. Function overloading can be done in the same class or in sub classes.


How overloaded functions are executed


When any function calling statement is executed, compiler checks the name of the function first and then the argument list. The binding between the function calling statement and the function definition is done accordingly.


Utility of function overloading


Function overloading reduces complexity of a program. Functions with same name but different body statement means when these overloaded functions are being executed different actions are performed. For example take the case of ‘indexOf()’ function of String class. This function has four overloaded versions like ‘int indexOf(char ch)’, ‘int indexOf(char ch, int i)’ ‘int indexOf(String s)’ and ‘int indexOf(String s, int n)’. The first function takes a character as argument and returns the first occurance location of the character in the invoking string object. The second function returns the occurance of the argument character after the location specified by ‘int i’. The third and fourth function perform similar jobs as stated above but on argument strings.All the functions returns -1 if the character of string is not present in the invoking string object.

Constructor overloading is another important feature where via execution of constructors objects are created but different argument constructors will create objects differently. A simple example will demonstrate this feature perfectly.

class A
{
int a,b;
A()
{
}
A(int x, int y)
{
 a=x;
b=y;
}
}

The first constructor is without any argument which means it creates the object with default values on the data members. The second constructor sets two values on object data members while creating the object.

Monday, August 13, 2012

BlueJ Program On String Class Using indexOf And substring Functions


Here is a BlueJ program where user will enter a string like Computer and any character like
if enters 'c', the output will be - computer
if enters 't' , the output will be - ter
if enters 'r' , the output will be – r


import java.io.*;
class St
{
String str;
char ch;
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take()throws Exception
{
System.out.println("Enter the sentence:");
str=br.readLine();
System.out.println("Enter the character from where the sentence is to be extracted:");
ch=(char)br.read();
i=str.indexOf(ch);
if(i< 0)
System.out.println("Character is not present...");
else
{
str=str.substring(i);
System.out.println(str);
}
}
 public static void main(String args[])throws Exception
{
St tr=new St();
tr.take();
}

Monday, July 16, 2012

BlueJ Program On Displaying Armstrong Number Using Recursive Function

In this program user will enter any number and the program will show whether the entered number is armstrong number or not. I have used a recursive function to show the result.


import java.io.*;
class Armstrong
{
int n,f=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void take() throws Exception
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
f=no(n);
if(n==f)
System.out.println(n + " is an armstrong number");
else
System.out.println(n + " is not an armstrong number");
}
int no(int x)
{
int y,z;
if(x!=0)
{
y=x%10;
f=f+y*y*y;
x=x/10;
no(x);
}
return f;
}
public static void main(String args[]) throws Exception
{
Armstrong ob=new Armstrong();
ob.take();
}
}

Related PostBlueJ Programs on Number

Wednesday, September 7, 2011

Virtual Function and overriding in C++ programs


Complete study of virtual function, pure virtual function, overriding of virtual function are discussed here.

So far we have seen function overloading and operator overloading. Those are examples of polymorphism. Now we will see another implementation of polymorphism through virtual function. Virtual means existing in effect but not in reality. A virtual function means that does not really exists but appears real to some part of a program. 

Suppose we have a number of objects of different classes but we want to put them all in a list and perform a particular operation on them using the same function. Suppose we have three different classes line, circle and triangle. Each class contains a function draw () . The function body statements of the function in different class must be different. Suppose draw () function of line class will draw line, draw () function of circle class will draw a circle and so on. If we want to draw a number of lines, circles and triangles on the screen, we have to create an array of pointers that will contain the addresses of the objects. Using loop and pointer we can access the address of the objects and by calling the draw () function, we will get different output on the screen. When the loop has accessed any object of line class, the draw () function will draw a line. Similar effects will be observed in case of circle or triangle class.

<h2>Program on virtual function</h2>

 #include< iostream.h>
#include< conio.h>
class abc
{
public:
void display()
{
cout<< "\nInside base class.";
}
};
class xyz:public abc
{
public:
void display()
{
cout<< "\nInside 1st derived class.";
}
};
class mn:public abc
{
public:
void display()
{
cout<< "\nInside 2nd derived class.";
}
};
void main()
{
clrscr();
xyz ob;
mn ob1;
abc *ptr;
ptr=&ob;
cout<< "\nFor object of 1st derived class."<< endl;
ptr->display();
ptr=&ob1;
cout<< "\nFor object of 2nd derived class."<< endl;
ptr->display();
getch();
}

In the above program we have two derived classes of base or super class abc. All the three classes have a function void display (). Inside  the void main () we have created one pointer of the 1st class and two different objects of the derived classes. Next we have assigned the address of the derived class objects on the pointer of the base class. This will not generate any error as address of any derived class can be hold by a pointer of it’s super class. After assigning the address of derived classes we called the display () function. But each time the base class version of display() function will be executed as the pointer type matches with the base class, ignoring the content of the pointer. So this will not provide the required facility as stated earlier (line ,circle and triangle class ).
Now we will make some change in our program. Use the keyword virtual before the function definition. 

#include< iostream.h>
#include< conio.h>
class abc
{
protected :
int a,b;
public:
void take()
{
cout<< "\nEnter two values:"<< endl;
cin>>a>>b;
}
virtual void display()
{
cout<< "\nInside base class.";
}
};
class xyz:public abc
{
public:
void display()
{
cout<< "\nSum for 1st derived class="<< a+b;
}
};
class mn:public abc
{
public:
void display()
{
cout<< "\nSum for 2nd derived class:"<< a+b;
}
};
void main()
{
clrscr();
xyz ob;
mn ob1;
abc *ptr;
ptr=&ob;
cout<< "\nFor object of 1st derived class."<< endl;
ptr->take();
ptr->display();
cout<< "\nFor object of 2nd derived class."<< endl;
ptr=&ob1;
ptr->take();
ptr->display();
getch();
}

In the above program the void display () function of the derived classes were executed. If we want to execute the base class version of the display () function, we have create an object of the base class also and assign it’s address on the base class pointer. Next call to the display () function will execute the base class void display () function.

In the above program we have overridden the void display () of the base class in it’s derived classes, but it was not compulsory. We can define a function name void display1 () in class xyz to perform the same work as void display () function. In such case also we can assign the address of xyz class object on the pointer of it’s base class ( here abc *ptr ). Then through the pointer we can call the void take () function for the xyz class object but can not call the void display1 () function through the base class pointer as the base class has no intimation regarding the void display1 () function. But in some cases function overriding may become compulsory. In such situation the base class function ( which must be overridden by it’s derived classes ) should be <b>pure virtual function</b>. A pure virtual function has no body The declaration of a pure virtual function is like :- virtual void display ()=0; In general a virtual function of any super class is never executed. When this is true , the body of the virtual function of a any super class can be removed using the notation =0. When a super class contains any pure virtual function, sub classes which inherits the super class must <b>override the pure virtual function</b>.

A class containing at least a pure virtual function is called abstract class. An abstract  class cannot create any object. But pointers can be declared of an abstract class. Other sub classes can inherits an abstract class. Abstract class should be used as base class.

#include< iostream.h>
#include< conio.h>
class abc
{
protected :
int a,b;
public:
void take()
{
cout<< "\nEnter two 'int' values::";
cin>>a>>b;
}
virtual void display()=0;
};
class xyz:public abc
{
public:
void display()
{
cout<< "\nSum for 1st derived class="<< a+b;
}
};
class mn:public abc
{
public:
void display()
{
cout<< "\nSum for 2nd derived class:"<< a+b;
}
};
void main()
{
clrscr();
xyz ob;
mn ob1;
abc *ptr;
ptr=&ob;
cout<< "\nFor object of 1st derived class."<< endl;
ptr->take();
ptr->display();
cout<< "\nFor object of 2nd derived class."<< endl;
ptr=&ob1;
ptr->take();
ptr->display();
getch();
}

Tuesday, September 6, 2011

Constant function member in C++ programming


A constant function member can never modify any of its class’s data member.
const keyword to used to define constant function.

#include< iostream.h >
#include< conio.h >
class sample
{

private:
int count;
public:
sample()
{
count=0;
}
void change()
{
count=10;
}
void  show()const
{
count=12;/* this statement will show error in compile time */
cout<< "\nThe data member:"<< count;
}
};
void main()
{
clrscr();
sample sp1;
sp1.change();
sp1.show();
getch();
}

Monday, September 5, 2011

Member Functions defined outside the class in C++ program


In our previous examples we have defined all functions within the class body. C++ program allows defining functions outside the body of classes also. In such case we have to declare the functions within the class body.

Here is a C++ program to demonstratethe above feature.

#include< iostream.h>
#include< conio.h>
class Rect
{
private:
int len, br;
public:
void getData ();
void setData (int l, int b);
void displayData ();
void area ();
Rect (int a, int b);
Rect ();
};
void Rect::getData ()
{
cout<< endl<< "Enter Length and Breadth: -";
cin >>len >>br;
}
void Rect::setData (int l, int b)
{
len=l;
br=b;
}
void Rect::displayData ()
{
cout<< endl<< "Length="<< len;
cout<< endl<< "Breadth="<< br;
}
void Rect::area ()
{
int a, p;
a=len*br;
p=2*(len+br);
cout<< endl<< "Area="<< a;
cout<< endl<< "Perimeter="<< p;
}
Rect::Rect ()
{
}
Rect::Rect (int a, int b)
{
len=a;
br=b;
}
void main ()
{
clrscr ();
Rect r1 (2,3), r2, r3;
cout<< endl<< "For object number 1: -";
r1.displayData ();
r1.area ();
cout<< endl<< "For object number 2: -";
r2.setData (3,5);
r2.displayData ();
r2.area ();
cout<< endl<< "For object number 3: -";
r3.getData ();
r3.displayData ();
r3.area ();
getch ();
}

Sunday, September 4, 2011

String compare using operator overloading


In C Language, we use strcmp() or strcmpi() functions to compare two strings. In C++ programs also we use these functions to perform the same job. Operator overloading in C++ helps us to use equality operator to compare two strings in C++ programs.

Here is a C++ program to compare two strings using operator overloading.

#include< iostream.h >
#include< conio.h >
#include< string.h >
const int SIZE=40;
class String
{
private:
char str [SIZE];
public:
String ()
{
strcpy (str," ");
}
String (char ch [])
{
strcpy (str, ch);
}
void getString ()
{
cout<< "Enter the string: -";
cin.get (str, SIZE);
}
int operator == (String s)
{
if (strcmp (str, s.str)==0)
return 1;
else
return 0;
}
};
void main ()
{
clrscr ();
String s1, s2, s3;
s1="Satavisha";
s2="Suddhashil";
s3.getString ();
if (s3==s1)
cout<< "1st and 3rd string are same.";
else if (s2==s3)
cout<< "2nd and 3rd string are same.";
else
cout<< "All strings are unique.";
getch ();
}

Operator overloading is an important chapter in and Students can ask any related question through this blog.

Saturday, September 3, 2011

Constructor in C++ programs


Constructors are a special type of function whose body must be executed at the time of creating any object. Constructors are special because they have the same name as the class with no return type. A constructor body defines what occurs when an object of a class is created. However, if no explicit constructor is defined, compiler will supply a zero argument empty body constructor. So, to initialize the data members of an object we can use constructor.

#include< iostream.h >
#include< conio.h >
class Rect
{
private:
int len, br;
public:
void getData ()
{
cout<< endl<< "Enter Length and Breadth: -";
cin>>len>>br;
}
void setData (int l, int b)
{
len=l;
br=b;
}
void displayData ()
{
cout<< endl<< "Length="<< len;
cout<< endl<< "Breadth="<< br;
}
void area ()
{
int a, p;
a=len*br;
p=2*(len+br);
cout<< endl<< "Area="<< a;
cout<< endl<< "Perimeter="<< p;
}
Rect ()
{
}
Rect (int a, int b)
{
len=a;
br=b;
}
};
void main ()
{
clrscr ();
Rect r1 (2,3), r2, r3;
cout<< endl<< "For object number 1: -";
r1.displayData ();
r1.area ();
cout<< endl<< "For object number 2: -";
r2.setData (3,5);
r2.displayData ();
r2.area ();
cout<< endl<< "For object number 3: -";
r3.getData ();
r3.displayData ();
r3.area ();
getch ();
}

Here note that the constructor is defined twice in the class Rect. In this program this is a must, as the object r1 will be created after execution of the argument constructor and r2, r3 are created with the help of zero argument empty body constructor. In a class we can have two or more functions with the same name, as long as their parameter declarations are different. When this is the case the functions are said to be overloaded. Function overloading is an example of polymorphism.



Friday, November 5, 2010

Passing array to function in C Language

In the next example we will store some values in an array and the address of each location of the array will be passed to a function one after another . The function will display the value stored in the location.

#include< stdio.h>
 void dis(int *);
void main()
{
 int i;
 int arr[]={3,4,5,6};
 for(i=0;i< 4;i++)
 dis(&arr[i]);
 }
 void dis(int *p)
 {
 printf("\nValue=%d",*p);
}

Now the same program is modified so that  the entire array is passed to the function at a time.

#include<stdio.h>
 void dis(int *,int);
void main()
{
  int arr[]={3,4,5,6};
  dis(&arr[0],4);
 }
 void dis(int *p,int no)
 {
 int i;
 for(i=0;i< no;i++)
 {
 printf("\nValue=%d",*p);
 p++;
 }
}


Monday, August 9, 2010

program on string library function



strchr () is a predefined string function, very much used in C Language programming that takes two arguments-the first is a character array and the second is a single character.This function searches the  character in the string and if found returns the memory address of the character in the string , where it is found for the first time otherwise the function will return NULL
.
#include< stdio.h >
#include< string.h >
 void main ()
 {
 int i;
 char name [100],ch;
 clrscr();
 puts("Enter the string:-");
 gets(name);
 puts("Enter the character:-");
 scanf("%c",&ch);
 if(strchr(name,ch)!=NULL)
  printf("The character is found.");
  else
  printf("Not found.");
  getch();
 }

Sunday, August 8, 2010

C programs on string to check palindrome


Since the last few posts of our C programming language tutorial, we are continuing on array – character type. Actually string in C Language programming is a vast chapter and needs more time. We’ll see more and more programs on string in this C language programming tutorial.

Another string function is void strcpy (char ch1[],char ch2[]).This function copies one string to another. The first argument is the destination and the second argument is the source. The value in the second array will copied on the first array. If the first array has any value then the value will be lost and it will hold the value of the second argument, while the value in the second array will remain unchanged.

#include< stdio.h >
#include< string.h >
void main()
{
char ch1[50],ch2[50];
int i;
clrscr();
puts("Enter the first string:-");
gets(ch1);
puts ("Enter the second string:-");
gets (ch2);
printf ("Before calling the function the strings are:-\n");
printf ("%s", ch1);
printf ("\n%s", ch2);
strcpy (ch1, ch2);
printf ("\nAfter calling the function, the strings are:-\n");
printf ("%s", ch1);
printf ("\n%s", ch2);
 getch ();
 }
 }

Palindrome checking program on string
.
#include< stdio.h >
#include< string.h >
void main ()
{
char ch1 [50], ch2 [50];
int i, x=0;
clrscr ();
puts ("Enter the string:-");
gets (ch1);
for (i=strlen (ch1)-1; i >=0; i--)
{
ch2[x]=ch1 [i];
x++;
}
ch2[x] ='\0';
if (strcmp (ch1, ch2) ==0)
puts ("The string is palindrome.");
else
puts ("The string is not palindrome.");
getch ();
 }

Thursday, August 5, 2010

C programs on character type array using string functions


There are several string manipulating functions supported by C Programing Language. These functions are available in string.h header file. One of such function is int strlen(char ch[]). This function takes a character array as argument and returns the length of the string. Length of a string means the total number of characters in the character array including blanks.

Here is an program on C Language to demonstrate the above feature

#include< stdio.h >
#include< string.h >
void main()
{
 char ch[20];
 int i;
 puts("Enter your name:-");
 gets(ch);
 i=strlen(ch);
 printf("Your name contains %d characters including space.",i);
 getch();
 }


In the above C program, the user may have entered his/her name with surname and at the end may have put a full stop. So the above program will show the length of the string including the space and the full stop. But actually the length means the total number of characters excluding the space and full stop. Our next C program on string will be a modified version of the above program that will display the number of characters in the name of the user.

C program to calculate length of a string without using library function

#include< stdio.h >
void main()
{
 char ch[20];
 int i=0,length=0;
 clrscr();
 puts("Enter your name:-");
 gets(ch);
 while(ch[i]!='\0')
 {
 if((ch[i]!=' ')&&(ch[i]!='.'))
 length++;
 i++;
 }
 printf("Your name contains %d characters .",length);
 getch();
 }

Note that in this above program string.hheader file is not used to calculate the length of the string.

Subscribe via email

Enter your email address:

Delivered by FeedBurner