Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Wednesday, 24 July 2013

C Program To Find The Number Of Occurrences Of a Character In a String

Hello Guys,
In this post, I'll explain how to find the number of occurrences of a character in a string, program for which is really very simple.

A string is C is defined to be sequence of characters terminated by the special character '\0'. The special character '\0' is called the Null Character and it is to indicate the end of a string.

Let us straight away understand the following program.

str is declared  to be a string variable of size 100. This length can be varied according to user. I have taken it to be 100 so that a sentence can be easily accommodated. Its work is to collect a string(input) from the user. 


ch is declared to be a variable of char type and it is to collect a character(input), the number of occurrences of which in str is to be found out. i and count are declared to be variable of int type. the variable i is used to traverse the characters in str and count is to collect the number of occurrences of ch in str(output).


After a string is accepted into str, a for loop is set up to traverse each character of the string. Within the body of the loop, each character of the string is checked against ch for equality.


In case of a match, the variable count is incremented. When this loop exits, the variable count will have the number of occurrences of the given character in the given string.



C Program To Find The Number Of Occurrences Of a Character In a String:



/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
char str[100], ch;
int i, count;

clrscr();
printf("Enter a String: ");
gets(str);
fflush(stdin);
printf("\nEnter a Character: ");
scanf("%c",&ch);

/* Finding the no. of occurrences of character 'ch' in 'str' begins */
count=0;

for(i=0 ; str[i]!='\0' ; i++)
if(str[i]==ch)
count++;

/* Find the no. of occurrences of 'ch' in 'str' ends */

printf("\nNo. of occurrences of '%c' in '%s' is %d",ch,str,count);
getch();
}

Program Output:

C Program To Find The Number Of Occurrences Of a Character In a String


Please Comment If You Liked The Post.



Thursday, 18 July 2013

Find Factorial Of a Number Using Recursion C Program

Hello Guys,
In this post I'll explain what is Recursion and how it can be used to calculate the factorial of a number in C.

Suppose f1(), f2() and f3() are three functions. The function f1() can call f1(), in turn, f2() can call f3(). Likewise, nesting of the function calls can be to any level depending on the requirement. There is one more possibility with regard to functions, which needs to be mentioned. That is, a function f() calling itself. The phenomenon of a function calling itself is called Recursion. The function involved in the process is referred to as a recursive function.

When a recursive function is employed to solve any problem, care needs to be taken to see to it that the function does not call itself again at some point of time by which the solution of the problem has been arrived at. This is accomplished with the help of a terminating condition.

The program is quite simple. Function Fact() is defined with an argument of int type and is made to return a Value of int type. The purpose of this function is to find the factorial of an integer number passed as an argument to it and return the result. It works as follows:

If the value of n is 1, the function returns 1. Of n>1 then, as long as n>1, fact(0 is called recursively by passing one less than the previous number. Once argument to fact() becomes 1, the function call is replaced by 1. The value of the resultant expression constructed is assigned to the variable f and is then returned to the main(). 

Find Factorial Of a Number Using Recursion C Program:



/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

int fact(int number);

int main(void)
{
 int number;
 int f;
 clrscr();

 printf("\nEnter The Number: ");
 scanf("%d",&number);

 f = fact(number);
 printf("\nFactorial of %d =  %d",number,f);

 getch();
 return 0;
}

int fact(int number)
{
 int f;
 if(number==0)
 return(1);

 else
 f = number * fact(number-1); // Recursion
 return f;
}


Program Output:


Find Factorial Of a Number Using Recursion C Program

Please Comment If You Liked The Post.


Saturday, 13 July 2013

Generate Prime Numbers Within a Range Of Numbers C Program

Hello Guys
In this post, I will explain the C Program, how to generate Prime Numbers within a range of numbers. prime number (or a prime) is a natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) greater than 1 that has no positive divisors other than 1 and itself.natural number  is called a prime or a prime number if it has exactly two positive divisors, '1' and the number itself.

Now I will explain how to find out all the prime numbers within a range of numbers, which will be taken as an input from the user. The code is self-explained and quite easy.

First, we take the upper and lower limit range as an input from the user. Then in the main logic begins. We initiate a loop variable 'i' from the lower limit till the upper limit. Inside that, we use a temporary variable 'k' which takes the value same as 'i'. Now for every 'k' another loop runs, in which we check all numbers from 2 to k/2 (As no number can have any divisor greater than [number/2] ) and see that if any remainder comes or not. If any remainder comes, flag variable becomes false or 0. But in those cases where the flag variable remains 1, that number is a Prime number and is printed on the screen.

Generate Prime Numbers Within a Range Of Numbers C Program:


/* Double-Click To Select Code */

#include <stdio.h>
#include <conio.h>

int main(void)
{
 int m,n,i,j,k,flag;
 clrscr();

 printf("\nEnter The Lower Limit: ");
 scanf("%d",&m);
 printf("\nEnter The Upper Limit: ");
 scanf("%d",&n);

 printf("\nPrime Numbers Between %d & %d Are:\n",m,n);
 for(i=m ; i<=n ; i++)
 {
  k=i;
  flag=1;
  for(j=2 ; (j<=k/2)&&flag ; j++)
  {
   if(k%j==0)
   flag=0;
  }

  if(flag)
  printf("%3d \n",i);
 }

 getch();
 return 0;
}


Program Output:


Generate Prime Numbers Within a Range Of Numbers C Program


Please Comment If You Liked The Post.



Monday, 24 June 2013

Multiple Inheritance And Its C++ Program

Hi Guys,
Today we are going to discuss about the last type of Inheritance we have seen till yet, Multiple Inheritance.
Have you learnt about Inheritance  and its different types? Check Out Now:

There are 5 types of Inheritances used in C++:
1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

A class can inherit the attributes of two or more classes as shown in fig. A. This is known as Multiple Inheritance. Multiple Inheritance allows us to combine the features of several existing classes as a starting point for defining new classes. It is like a child inheriting the physical features of one parent and the intelligence of the another.

Multiple Inheritance And Its C++ Program
fig. (A)
The syntax of a derived class with multiple base classes is as follows:

class D: visibility B1visibility B1...
{
          ..........
          .......... (Body Of D)
          ..........
};

where, visibility modes may be either public or private. The base classes are separated by commas.

Example:

   class P : public M, public N
   {
        public:
            void display(void);
   };

The following program shows the program code illustrating how all the three classes are implemented in Multiple Inheritance mode.

Multiple Inheritance C++ Program:

/* Double-Click To Select Code */
#include<iostream.h>
#include<conio.h>
class M
{
 protected:
  int m;
 public:
  void get_m(int x)
  {
   m = x;
  }
};

class N
{
 protected:
  int n;
 public:
  void get_n(int y)
  {
   n = y;
  }
};

class P : public M, public N
{
 public:
  void display()
  {
   cout<<"M = "<<m<<"\n\n";
   cout<<"N = "<<n<<"\n\n";
   cout<<"M*N = "<<m*n<<"\n";
  }
};

void main()
{
 clrscr();
 P p;
 p.get_m(10);
 p.get_n(20);
 p.display();
 getch();
}


Program Output:

Multiple Inheritance And Its C++ Program

Please Comment If You Liked The Post.


Wednesday, 19 June 2013

Hybrid Inheritance Using Virtual Base Class C++ Program

We have discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its fourth type, that is, Hybrid Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchical Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

There could be situations where we need to apply two or more types of inheritance to design a program. For example, consider the case of processing the student results. Assume that we have to give weight-age for sports before finalizing the results. The weight-age for sports is stored in a separate class called sports. In this case, we will need both Multiple and Multilevel Inheritance. 

Consider another case, where all three kinds of inheritance, namely, Multilevel  Multiple and Hierarchical Inheritance, are needed. This is illustrated in the following picture. The 'child' has two direct base classes 'parent1' and 'parent2' which themselves have a common base class 'grandparent'. The child inherits from 'grandparent' via two separate paths. It can also inherit directly as shown by the red line. The 'grandparent' is sometimes known as the Indirect Base Class.


Hybrid Inheritance C++ Program

Inheritance by the above method directly might pose some problems. All the public and protected members of 'grandparent' are inherited into 'child' twice, first via 'parent1' and second via 'parent2'. This means child would have duplicate sets of members inherited from 'grandparents'. This introduces ambiguity and should be avoided.

Hence we use a method called virtual base class. C++ takes necessary care to see that only one copy of that class is inherited, regardless of how many inheritance paths exist between the virtual class and derived class.



Friday, 7 June 2013

Hierarchical Inheritance And Its C++ Program

We have discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its third type, that is, Hierarchical Inheritance.

In Object Oriented Programming, the root meaning of inheritance is to establish a relationship between objects. In Inheritance, classes can inherit behavior and attributes from pre-existing classes, called Base Classes or Parent Classes.The resulting classes are known as derived classes or child classes

There are 5 types of Inheritances used in C++:

1) Single Inheritance
2) Multilevel Inheritance
3) Hierarchial Inheritance
4) Hybrid Inheritance
5) Multiple Inheritance

So in Hierarchical Inheritance, we have 1 Parent Class and Multiple Child Classes, as shown in the pictorial representation given on this page, Inheritance. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level. One example could be classification of accounts in a commercial bank or classification of students in a university.

In C++, such problems can be easily converted into hierarchies. The base class will include all the features that are common to the subclasses. A subclass can be constructed by inheriting the properties of the base class. A subclass can serve as a base class for the lower level classes and so on.

A derived class with hierarchical inheritance is declared as follows:

class A {.....};            // Base class
class B: public A {.....};             // B derived from A
class C: public A {.....};             // C derived from A

This process can be extended to any number of levels. Let us understand this concept by a simple C++ program:

C++ Program For Hierarchical Inheritance:

/* Double-Click To Select Code */

#include<iostream.h>
#include<conio.h>

class polygon
{
 protected:
  int width, height;
 public:
  void input(int x, int y)
  {
   width = x;
   height = y;
  }
};

class rectangle : public polygon
{
 public:
  int areaR ()
  {
   return (width * height);
  }
};

class triangle : public polygon
{
 public:
  int areaT ()
  {
   return (width * height / 2);
  }
};

void main ()
{
 clrscr();
 rectangle rect;
 triangle tri;
 rect.input(6,8);
 tri.input(6,10);
 cout <<"Area of Rectangle: "<<rect.areaR()<< endl;
 cout <<"Area of Triangle: "<<tri.areaT()<< endl;
 getch();
}

Program Output:



Hierarchical Inheritance C++ Program

Please Comment If You Liked The Post.