Calculate Roots Of a Quadratic Equation Using C Program

Hi everyone
In this post, we're going how to write a C program to calculate the roots of a quadratic equation. As we know that a quadratic equation is of a form like:

ax^2+bx+c=0

So we won't go into much details. Also you guys must be knowing to calculate the roots of a quadratic equation directly, having formula:

Roots = ( -b + (b^2 - 4ac) ) / 2a ( -b - (b^2 - 4ac) ) / 2a

So we are just going to use the same formula in our C code. So Let's begin...

C Program To Calculate Roots Of a Quadratic Equation:

/* Double-Click To Select Code */

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

void main()
{
float a,b,c,root1,root2,x,real,im;
clrscr();

printf("\n\nEnter the value of a: ");
scanf("%f",&a);
printf("\nEnter the value of b: ");
scanf("%f",&b);
printf("\nEnter the value of c: ");
scanf("%f",&c);

x = (b*b)-(4*a*c);

if(x>0)
{
root1 = (-b+sqrt(x))/(2*a);
root2 = (-b-sqrt(x))/(2*a);       //ROOTS ARE UNIQUE
printf("\nThe roots of the equation are: %.2f and %.2f",root1,root2);
}

else if(x==0)
{
root1 = -b/(2*a);
root2 = root1;  //ROOTS ARE SAME
printf("\nThe roots of the equation are: %.2f and %.2f",root1,root2);
}

else
{
real = -b/(2*a);
im = sqrt(-x)/(2*a);  // ROOTS ARE COMPLEX
printf("\nThe roots of the equation are: %.2f+j%.2f and %.2f-j%.2f",real,im,real,im);
}

getch();
}

Program Explanation:

The program is self explanatory in itself. First we take the coefficients of the quadratic equation as input from the user. Then on the basis of its determinant,i.e, b^2 - 4*a*c, if its greater than 0 or equal to 0 or less than 0. In each of the case, we can get different types of roots, Unique, Equal or Complex respectively. Using the formula as I described in the beginning of this post, we calculate roots, with an exception in case of complex roots, whereby, we have to find real and imaginary parts of the roots individually, using the formula:
Real Part = -b/(2*a)
Imaginary Part = sqrt(-x)/(2*a) -> Since determinant is negative here, we make it positive by multiplying an extra '-'.

Program Output:

Please Comment If You Liked The Post.

C Code To Concatenate Two Strings

Hello guys,
In this post, I'll explain the C Code To Concatenate Two Strings.

As we all know that, the process of appending one string to the end of another string is called concatenation. If s1 and s2 are two strings and when s2 is appended to the end of s1, s1 and s2 are said to be concatenated. The string s1 then contains the original string plus the string contained in s2. Similar to copying and comparing, appending s2 to s1 should be done on a character by character basis. C provides strcat() built-in function to concatenate two strings.

The prototype of strcat() is as follows:

strcat(s1,s2);

C Program To Concatenate Two Strings:

/* Double-Click To Select Code */

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

void main()
{
char str1[20]="abc", str2[20]="def", str3[20]="ghi";
int i,j;
clrscr();

printf("str1 = %s | str2 = %s \n",str1,str2);

/* Concatenation of str1 and str2 without using strcat() begins */

for(i=0 ; str1[i]!='\0' ; i++);
for(j=0 ; str2[j]!='\0' ; j++)
{
str1[i+j] = str2[j];
}

str1[i+j]='\0';
printf("\nAfter concatenation str1 = %s \n",str1);

/* Concatenation of str1 and str2 without using strcat() begins */
strcat(str1,str3);
printf("\nstr1 = '%s' \n",str1);
strcat(str1,"jkl");
printf("\nstr1 = '%s' \n",str1);

printf("\n\n *WWW.CODINGBOT.NET*");
getch();
}

Program Output:

Please Comment If You Liked The Post.

C Code To Find The Length Of a String

Hello guys,
In this post, I'll explain the C Code how to find the length of a string, by 2 methods, first by using strlen() function and second by normal programming.

Length of a string is defined to be the number of characters in it excluding the null character '\0'. To find the length of a string, we need to scan through the string, count the number of characters till the null character is reached. C provides a built-in function namely, strlen() to find the length of a string.

C Program To Find The Length Of a String:

/* Double-Click To Select Code */

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

void main()
{
char str[100];
int i,length;
clrscr();

printf("Enter a String: ");
gets(str);

/* Finding the length of str without using strlen() begins */

length=0;
for(i=0 ; str[i]!='\0' ; i++)
length++;
printf("\nLength of '%s' = %d\n",str,length);

/* Finding the length of str using strlen() begins */

length = strlen(str);
printf("Length of '%s' using strlen = %d \n",str,length);

printf("\n\n *WWW.CODINGBOT.NET*");
getch();
}

Program Explanation:

str is declared to be an array of char type and of size 100. Length and i are declared to be variables of int type. str is to collect the input string. Variable length is to collect the length of the string in str. The variable i is to scan through the string accessing each character.

A string is read into str through the keyboard  The following segment finds the length of str without strlen():

length = 0;
for(i=0 ; str[i] != '\0' ; i++)
length++;

Length is initialized to 0 before scanning through the string begins. When the loop is entered, scanning through the string begins. During the course of scanning, if the character is not fund to be null character '\0', length is incremented by one. The loop is exited when the null character is reached. So, when the loop completes, length collects the length of str.
The length of str is found out using strlen() built-in function also.

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:

Please Comment If You Liked The Post.

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:

Please Comment If You Liked The Post.

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:

Please Comment If You Liked The Post.

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. fig. (A) The syntax of a derived class with multiple base classes is as follows: class D: visibility B1, visibility 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:

Please Comment If You Liked The Post.

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++:

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++:

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:

Please Comment If You Liked The Post.

Multilevel Inheritance And Its C++ Program

Hello Guys,
As I have already discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its second type, that is, Multilevel 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 Multilevel Inheritance, we actually have 2 Base Classes in total and 1 Child class. The class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.

The class B is known as Intermediate Base Class since it provides a link for the inheritance between A and C. The chain A B C is known as Inheritance Path. For pictorial representation, follow this link: Inheritance.

A derived class with multilevel inheritance is declared as follows:

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

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

C++ Program For Multi-level Inheritance:

/* Double-Click To Select Code */

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

class student
{
protected:
int roll;
public:
void get_number(int a)
{
roll = a;
}

void put_number()
{
cout<<"Roll Number: "<<roll<<"\n";
}
};

class test : public student
{
protected:
float sub1;
float sub2;
public:
void get_marks(float x,float y)
{
sub1 = x;
sub2 = y;
}

void put_marks()
{
cout<<"Marks in Subject 1 = "<<sub1<<"\n";
cout<<"Marks in Subject 2 = "<<sub2<<"\n";
}

};

class result : public test
{
private:
float total;
public:
void display()
{
total = sub1 + sub2;
put_number();
put_marks();
cout<<"Total = "<<total<<"\n";
}
};

void main()
{
clrscr();

result student;
student.get_number(83);
student.get_marks(99.0,98.5);
student.display();

getch();
}

Program Output:

Please Comment If You Liked The Post.

Single Inheritance And Its C++ Program

Hello Guys,
As I have already discussed in my previous post, what is Inheritance and its different types in C++, so today we are going to discuss about its first type, that is, Single 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 Single Inheritance, we have one base class and one child class. It means that, there is only one child class, which is inheriting attributes and behavior from only one base class, as shown below:

Let us consider a simple example to illustrate Single Inheritance. The following program shows a base class 'B' and a derived class 'D'. Both have a private data member each, integer 'a' and integer 'c' respectively. Base class has a function to assign values to its data members. Derived class inherits from base class and its function then calls data members from base class. Then the logical operation is performed and the result is displayed.

C++ Program For Single Inheritance:

/* Double-Click To Select Code */

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

class B
{
private:
int a;

public:
int b;
void set_ab()
{
a = 5;
b = 10;
}

int get_a()
{
return a;
}
};

class D : public B
{
private:
int c;
public:
void mul()
{
c = b*get_a();
}

void display()
{
cout<<"a = "<<get_a()<<"\n";
cout<<"b = "<<b<<"\n";
cout<<"c = a*b = "<<c<<"\n\n";
}
};

void main()
{
clrscr();
D d;

d.set_ab();
d.mul();
d.display();

d.b = 20;
d.mul();
d.display();

getch();
}

Program Output:

Please Comment If You Liked The Post.

C++ Program To Show Use Of Objects In Classes

Hi Guys,
In this post, we'll learn what are objects, the most important entity for which C++ is known better than C language. The main reason of C++ programming is to add the ability to create objects and classes are a central feature of C++ that support OOPS aka Object-Oriented Programming and classes are often called as user-defined types.

Objects are the basic run-time entities in an object-oriented system. They may represent a person, place, a bank account, a table of data or any other item that the program has to handle.When a program is executed, the objects interact by sending messages to one another.

Objects can interact without having to know the details of each other's data or code. Each object contains data, and code to manipulate the data. Well here is an example:

 Two Ways Of Representing An Object

C++ Code To Show Use Of Objects In Classes:

/* Double-Click To Select Code */

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

class product  //Class name
{
private:  // Private data member not accessible by object
int number;
float cost;

public:
void getdata(int a,float b);  //Function declaration
void putdata();
};

void product::getdata(int a,float b)  //Function definition
{
number = a;
cost  = b;
}

void product::putdata()
{
cout<<"Number : "<<number<<endl;
cout<<"Cost : "<<cost<<endl;
}

void main()
{
clrscr();
product p;   //Declaration of object
cout<<"\nObject P"<<"\n";

p.getdata(100,299.95);  //Only public members are accessible by object
p.putdata();

product q;
cout<<"\nObject Q"<<"\n";

q.getdata(200,175.50);
q.putdata();
getch();
}

Program Output:

Please Comment If You Liked The Post .

Shell Sort C Code And Algorithm

Shell sort is an in-place comparison sort. Donald Shell published the first version of this sort in 1959. It generalizes an exchanging sort, such as insertion or bubble sort, by starting the comparison and exchange of elements with elements that are far apart before finishing with neighboring elements. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange.

Shellsort is a multi-pass algorithm. Each pass is an insertion sort of the sequences consisting of every h-th element for a fixed gap h (also known as the increment). This is referred to as h-sorting. Shell sort is unstable,that is, it may change the relative order of elements with equal values.

It has "natural" behavior, in that it executes faster when the input is partially sorted.

 Shell Sort In Action

Algorithm/Pseudo-Code:

Using Marcin Ciura's gap sequence, with an inner insertion sort.
/* Double-Click To Select Code */
# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]

foreach (gap in gaps)
{
# Do an insertion sort for each gap size.
for (i = gap; i < n; i += 1)
{
temp = a[i]
for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
{
a[j] = a[j - gap]
}
a[j] = temp
}
}

Here is the C Code for Shell Sort:

/* Double-Click To Select Code */

#include <stdio.h>
#include <conio.h>
#define MAX 20

void main()
{
int arr[MAX],i,j,k,n,increment;
clrscr();
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("\nEnter %d elements : \n",n);
for(i=0 ; i<n ; i++)
scanf("%d",&arr[i]);

printf("\nUnsorted list is:\n");
for (i = 0; i < n; i++)
{
printf("%4d",arr[i]);
}
increment=5;

/*ACTUAL LOGIC STARTS*/

while(increment>=1)
{
for(j=increment ; j<n ; j++)
{
k=arr[j];
for(i = j-increment ; i >= 0 && k<arr[i] ; i = i-increment)
arr[i+increment]=arr[i];
arr[i+increment]=k;
}
increment=increment-2;  /*Decrease the incrementement*/
}
printf("\n\nSorted list is:\n");
for (i = 0 ; i<n ; i++)
{
printf("%4d",arr[i]);
}
printf("\n\n *WWW.CODINGBOT.NET*");
getch();
}

Output of Program:

Please Comment If You Liked This Post !!