Showing posts with label projects. Show all posts
Showing posts with label projects. Show all posts

Tuesday, April 1, 2014

C Program to Calculate Area of Circle using Pointer

Calculate Area of Circle using Pointer :

#include<stdio.h>

void areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}

void main( )
{
int radius ;
float area, perimeter ;

printf ( "nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;

areaperi ( radius, &area, &perimeter ) ;

printf ( "Area = %f", area ) ;
printf ( "nPerimeter = %f", perimeter ) ;
}

Output:

Enter radius of a circle 5
Area = 78.500000
Perimeter = 31.400000

C Program to Calculate Area of Square

C Program for Beginners : Area of Square

Shape : Square
   Formula : side * side
Definition :
  1. A plane rectangle with four equal sides and four right angles 
  2. A four-sided regular polygon
  3. You can compute the area of a square if you know the length of its sides
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int side,area;
clrscr();  // Clear Screen

printf("nEnter the Length of Side : ");
scanf("%d",&side);

area = side * side ;

printf("nArea of Square : %d",area);
getch();
}
Output :
Enter the Length of Side : 5
Area of Square : 25

C Program to Calculate Area of Rectangle

C Program for Beginners : Area of Rectangle

Shape : Rectangle
formula : area = l * b
Definition
  1. A plane figure with 4 sides and 4 right angles and having Equal Opposite Sides
  2. Adjucent sides makes an angle of 90 degree
  3. You can compute the area of a Rectangle if you know its length and breadth
Program :
#include<stdio.h>
#include<conio.h>

void main()
{
int length,breadth,side;
clrscr();  // Clear Screen

printf("nEnter the Length of Rectangle : ");
scanf("%d",&length);

printf("nEnter the Breadth of Rectangle : ");
scanf("%d",&breadth);

area = length * breadth;

printf("nArea of Rectangle : %d",area);
getch();
}
 
Output :
Enter the Length of Rectangle  : 5
Enter the Breadth of Rectangle : 4
Area of Rectangle : 20

C Program to Calculate Area of Circle

C Program for Beginners : Area of Circle

Shape : Circle
   Formula : Π * r * r
 Definition :
  1. Ellipse in which the two axes are of equal length
  2. Plane curve generated by one point moving at a constant distance from a fixed point
  3. You can compute the area of a Circle if you know its radius.
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
float radius,area;
clrscr();  // Clear Screen

printf("nEnter the radius of Circle : ");
scanf("%d",&radius);

area = 3.14 * radius * radius;

printf("nArea of Circle : %f",area);
getch();
}
Output :
Enter the radius of Circle : 2.0
Area of Circle : 6.14

C Program to Calculate Area of Right angle Triangle

C Program for Beginners : Area of Right Angled Triangle

Right angle Triangle
 Definition :
  1. Triangle having one angle of measure 90 degree is called Right angle Triangle.
  2. Sides of Triangle are : base , height , hypotenuse.
  3. You can compute the area of a Tr. if you know its any two sides.

Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int base,height;
float area;
clrscr();  // Clear Screen

printf("nEnter the base of Right Angle Triangle : ");
scanf("%d",&base);

printf("nEnter the height of Right Angle Triangle : ");
scanf("%d",&height);

area = 0.5 * radius * radius;

printf("nArea of Right Angle Triangle : %f",area);
getch();
}
Output :
Enter the base of Right Angle Triangle   : 4
Enter the height of Right Angle Triangle : 8
Area of Right Angle Triangle : 16.0

C Program to Calculate Area of Equilatral Triangle

C Program for Beginners : Area of Square

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

int main()
{
int side;
float area,r_4;

r_4 = sqrt(3) / 4 ;

printf("nEnter the Length of Side : ");
scanf("%d",&side);

area = r_4 * side * side ;

printf("nArea of Equilateral Triangle : %f",area);
return(0);
}
Output :
Enter the Length of Side : 5
Area of Equilateral Triangle : 10.82

Properties of Equilateral Triangle :

  1. Equilateral triangle is a triangle in which all three sides are equal .
  2. All angles are of measure 60 degree
  3. A three-sided regular polygon

Formula to Calculate Area of Equilateral Triangle :


Explanation of Program :

First of all we have to find the value of Root 3 / 2. So we have used following statement to compute the value.
r_4 = sqrt(3) / 4 ;
Now after computing the value of the Root 3 by 2 we have multiplied it by Square of the side.
area = r_4 * side * side ;

Wednesday, April 17, 2013

Check binary tree

A tree is called binary tree if each node contains zero,one or two sub-trees.In this program,tree is first created.Then the function check_complete,checks every node recursively.Each node is parsed till it reaches NULL.If both the left child and right child are NULL then it is called binary tree.

#include < stdio.h >
#include < conio.h >
#include < alloc.h >
#define new_node (struct node*)malloc(sizeof (struct node))

struct node
{
    int data;
    struct node *lc;
    struct node *rc;
};
struct node *create_bin_pre_rec();

void main()
{
    struct node *r;
    int reply;   
    clrscr();
    printf("\nCreate a binary tree \n");
    r = create_bin_pre_rec();   
    printf("\n The binary tree is \n");
    print_bin_pre_rec(r);
    reply = check_complete(r);
    if( reply == 1 )
        printf("\n Complete tree ");
    else
        printf("\n Not complete tree ");
}

struct node *create_bin_pre_rec()
{
    struct node *c;
    int data;
    printf("\nData : ");
    scanf("%d",&data);
    if( data == -1)
        return(NULL);
    else
    {
        c = new_node;
        c->data = data;
        c->lc = create_bin_pre_rec();
        c->rc = create_bin_pre_rec();
        return(c);
    }
} // create

int print_bin_pre_rec(struct node *t)
{
    if( t != NULL)
    {
        printf("%4d",t->data);
        print_bin_pre_rec(t->lc);
        print_bin_pre_rec(t->rc);
    }//if
    return;
} // print

int check_complete(struct node *t)
{
    int reply;
    if( t == NULL)
        return(1);
    else
        if( t->lc == NULL && t->rc == NULL)
            return(1);
        else
            if( t->lc != NULL && t->rc == NULL)
                return(0);
            else
            if( t->lc == NULL && t->rc != NULL)
                return(0);
            else
            {
                reply = check_complete(t->lc);
                if ( reply == 1 )
                    reply = check_complete(t->rc);
                    return(reply);
    } // else
} // check complete

Sort n values using quick sort method

Suppose n different values are stored in numeric array a from the location 0 to n-1.Consider a dummy value which is largest among all input values. Place this dummy value at the n+1 location i.e. logical position a[n].In short place this dummy value after the last input value.The dummy value is used for sorting as follows -
1. a[n]=dummy value
2. Consider two indices l(low) and h(high).Initialize l to 0 and h to n-1.
3. If the lower limit is less than the higher limit then do the following -
    a. Consider temporary variable k.Copy the content of the position l i.e. a[l] into k.Here k acts as a reference value for creating two partitions.
    b. Consider two indices i and j.Initialize i to lower limit l and j to higher limit h+1.
    c. While i < j do the following
        i. While value of a[i] is less than or equal to k and i is less than h,increment i.
        ii. While value of a[j] is greater than or equal to k and j is greater than l ,decrement j.
        iii. If i is less than j ,then swap the values of a[i] and a[j].
    d. If j is not equal to l ,then swap the values of a[j] and a[l].
    e. After swapping a[l] and a[j],two partitions are created.First partition is from l to j-1 and second partition is from j+1 to h.
4. Use the steps from 2 to 3 for each partition till no more partition is possible.
5. After creating all the partitions , the input values are sorted automatically.

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

void main()
{
    int a[50];
    int n;
    clrscr();
    printf("\nEnter n: ");
    scanf("%d",&n);
    read_data(a,n);
    a[n]=9999;
    printf("\nBefore sort :");
    print_data(a,n);
    qsort(a,0,n-1,n);
    printf("\nAfter sort :");
    print_data(a,n);
}

int read_data(int a[],int max)
{
    int i;
    printf("\nEnter %d values \n",max);
    for(i=0; i < max; i++)
    {
        scanf("%d",&a[i]);
    }
    return;
}

int print_data(int a[],int max)
{
    int i;
    for(i=0; i < max; i++)
    {
        printf("%4d",a[i]);
    }
    return;
}

int quick_sort(int a[],int l,int h,int n)
{
    int i,j,k,t;
    if(l < h)
    {
        k=a[l];
        i=l;
        j=h+1;
        while( i < j)
        {
            while( i < h && a[i] <= k)
                i++;

            while( j > l && a[j] > =k)
                j--;

            if( i < j)
            {
                  t=a[i];
                  a[i]=a[j];
                  a[j]=t;
            }
        }
        if( l != j)
        {
            t=a[l];
            a[l]=a[j];
            a[j]=t;
        }
        printf("\nOutput :");
        print_data(a,n);
        qsort(a,l,j-1,n);
        qsort(a,j+1,h,n);
    }
    //print_data(a,n);
    return;
}

Sort structure type using insertion sort method

In this case,the input is sorted while reading and placing it in the array.In all other methods,all input values are placed in array before applying the actual sorting procedure.But here ,the values are sorted while reading them from console.Here the student details are accepted as input and stored in structure type array.Then it is sorted as per the value of the percentage.
Basic steps are as follows -
-Read a value form console.
-In order to place it in given array find its position in such a way that after its insertion the resultant data must be in sorted order.
-For this purpose,start shifting the values from bottom of the array downward by one position till getting a proper position.
-Insert a new value after getting its proper position.


//... C Language Program to sort the Student Records by using an Insertion Sort method

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

struct stud
{
    int roll;
    char name[15];
    float per;
};

void main()
{
    struct stud a[50], t;
    int n;

    clrscr();

    printf("\n C Language Program to sort the Student Records by using Insertion Sort method ");
    printf("\n To sort the Student Records in Dercreasing Order of % (Percentage) \n");

    printf("\n Enter How Many Records [ i.e. Size of Array (n) ] : ");
    scanf("%d", &n);

    insrtn_srt(a, n);

    printf("\n %d Values After Sorting are \n", n);
    print_data(a, n);

} // main

int print_data( struct stud a[], int n )
{
    int i;

    printf("\n Roll No. \t Name \t Percentage (%) \n");
    for(i = n - 1; i >= 0; i--)
            printf("\n \t %d \t %s \t %0.2f", a[i].roll, a[i].name, a[i].per);
    return;
} // print_data

int insrtn_srt( struct stud a[], int n )
{
    int i, j, bottom;
    struct stud t;

    bottom = -1;
    for(j = 0; j < n; j++)
    {
        printf("\n Roll Number : ");
        scanf("%d", &t.roll);
        printf("\n Name : ");
        flushall();
        scanf("%s", t.name);
        printf("\n Percentage (%) : ");
        scanf("%f", &t.per);
        i = bottom;
        while( a[i].per > t.per && i != -1)
        {
            a[i+1] = a[i];
            i--;
        } // while
        a[i+1] = t;
        bottom++;
    } // for
    return;
} // insrtn_srt

Draw shapes using graphics

This program shows how to draw different shapes using graphics.First the graphics is initialized.Then the generic functions are used to draw different shapes.

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

void main()
{
    /* initialization of graphics */
    InitGraphics();
   
    outtextxy(200, 10, "* Draw Shapes using Graphics *");
   
    /* draw circle */
    // DrawShape(1);
   
    /* draw arc */
    DrawShape(2);
   
    /* draw rectangle */
    DrawShape(3);
   
    /* draw pie slice */
    DrawShape(4);
   
    outtextxy(200, 400, "* Press any key to exit *");
   
    /* clean up */
    getch();
    closegraph();
    }
   
    /* This function initialize graphics */
    InitGraphics()
    {
    /* request auto detection */
    int gdriver = DETECT, gmode, errorcode;
   
    /* initialize graphics and local variables */
    initgraph(&gdriver, &gmode, "");
   
    /* read result of initialization */
    errorcode = graphresult();
   
    /* an error occurred */
    if (errorcode != grOk)
    {
    printf("Graphics error: %s\n", grapherrormsg(errorcode));
    printf("Press any key to halt:");
    getch();
    exit(1);/* terminate with an error code */
    }
    }
   
    /* This is generic function which draws different shapes */
    DrawShape(int shape)
    {
    switch(shape)
    {
    case 1:
    /* draw the circle */
    outtextxy(75, 40, "Circle");
    circle(100, 100, 50);
    break;
   
    case 2:
    /* draw arc */
    outtextxy(235, 40, "Arc");
    arc(250, 100, 0, 180, 50);
    break;
   
    case 3:
    /* draw a rectangle */
    outtextxy(350, 40, "Rectangle");
    rectangle(350,50,450,150);
    break;
   
    case 4:
    /* set fill style and draw a pie slice */
    outtextxy(100, 190, "Pie Slice");
    setfillstyle(EMPTY_FILL, getmaxcolor());
    pieslice(100, 250, 0, 0, 50);
    break;
    }
}

Saturday, April 6, 2013

cos in c - math.h

Cos function returns cosine of an angle(in radian).
1 radian = 57.2958(approximately).
Declaration: double cos(double);

C programming code

#include <stdio.h>
#include <math.h>
 
int main()
{
  double result, x = 1.0471;
 
  result = cos(x);
 
  printf("cos(%.4lf) = %.2lf\n", x, result);
 
  return 0;
}
Compiler used: 
GCC
Output of program: 
cos

abs c - math.h

abs is not a function but is a macro and is used for calculating absolute value of a number.

C programming code for abs

#include <stdio.h>
#include <math.h>
 
int main()
{
  int n, result;
 
  printf("Enter an integer to calculate it's absolute value\n");
  scanf("%d", &n);
 
  result = abs(n);
 
  printf("Absolute value of %d = %d\n", n, result);
 
  return 0;
}
You can implement you own function as follows:
long absolute(long value) {
  if (value < 0) {
    return -value;
  }
  else {
    return value;  
  }
}

log10

log10 function returns common logarithm (base is 10) of a number.
Declaration :- double log10(double number);

C programming code for log10

#include <stdio.h>
#include <math.h>
 
int main()
{
  double n, result;
 
  printf("Enter a number to calculate it's log(base is 10)\n");
  scanf("%lf", &n);
 
  result = log10(n);
 
  printf("Common log of %.2lf = %.2lf\n", n, result);
 
  return 0;
}
Compiler used: 
GCC
Output of program:

pow10 function

#include<stdio.h>
#include<math.h>
 
main()
{
   int x = 5;
   double result;
 
   result = pow10(x);
 
   printf("Ten raised to %d is %lf\n", x, result);
 
   return 0;
}

textcolor in c

textcolor function is used to change the color of drawing text in c programs.
Declaration :- void textcolor(int color);
where color is an integer variable. For example 0 means BLACK color, 1 means BLUE, 2 means GREEN and soon. You can also use write appropriate color instead of integer. For example you can write textcolor(YELLOW); to change text color to YELLOW. But use colors in capital letters only.

C programming code to change text color

#include<stdio.h>
#include<conio.h>
 
main()
{
   textcolor(RED);
   cprintf("C programming");
 
   getch();
   return 0;
}

C programming code for blinking text

#include<stdio.h>
#include<conio.h>
 
main()
{
   textcolor(MAGENTA+BLINK);
   cprintf("C programming");
 
   getch();
   return 0;
}
Note that we have used cprintf function instead of printf. This is because cprintf send formatted output to text window on screen and printf sends it to stdin.

wherex in c

wherex function return current horizontal cursor position.
Declaration :- int wherex();

C programming code for wherex

#include<stdio.h>
#include<conio.h>
 
main()
{
   int x;
 
   printf("Hello");
 
   x = wherex();
 
   printf("Horizontal cursor position from where this text appears = %d\n",x);
 
   getch();
   return 0;
}

kbhit in c

kbhit in c: kbhit function is used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file "conio.h". If a key has been pressed then it returns a non zero value otherwise returns zero.
Declaration : int kbhit();

C programming code for kbhit

#include <stdio.h>
#include <conio.h>
 
main()
{
   while (!kbhit())
      printf("You haven't pressed a key.\n");
 
   return 0;
}
As long as in the above program user doesn't presses a key kbhit() return zero and (!0) i.e. 1 the condition in while loop is true and "You haven't pressed a key." will be printed again and again. As a key is pressed from the keyboard the condition in while loop become false as now kbhit() will return a non-zero value and ( !(non-zero) = 0), so the control will come out of the while loop.

gotoxy in c

gotoxy in c: gotoxy function places cursor at a desired location on screen i.e. we can change cursor position using gotoxy function.
Declaration : void gotoxy( int x, int y);
where (x, y) is the position where we want to place the cursor.

C programming code for gotoxy

#include<stdio.h>
#include<conio.h>
 
main()
{
   int x, y;
 
   x = 10;
   y = 10;
 
   gotoxy(x, y);
 
   printf("C program to change cursor position.");
 
   getch();
   return 0;
}
Output:
gotoxy function code output
AttachmentSize
gotoxy.png4.17 KB

getche in c

getche function prompts the user to press a character and that character is printed on screen.

C code for getche

#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("Waiting for a character to be pressed from the keyboard to exit.");
 
   getche();
   return 0;
}
Run this program and press a character. Then view the user screen (Alt+F5) if using turbo c. You will find the character printed on the screen if you pressed a printable character. Try pressing enter or tab key (non printable) characters also.

getch in c

getch in c language: getch function prompts the user to press a character and that character is not printed on screen, getch header file is conio.h.

C programming code for getch

/* getch in c example */
#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("Waiting for a character to be pressed from the keyboard to exit.\n");
 
   getch();
   return 0;
}
When you will run this program, the program will exit only when you press a character, note that we are talking about a character so try pressing numlock, shift key etc (program will not exit if you press these keys) as these are not characters. Also try the above program by removing getch(), in this case program will exit without waiting for a character being pressed from keyboard.

How to use getch in c++

#include<iostream.h>
#include<conio.h>
 
main()
{
   cout << "Enter a character";
   getch();
}

getch in Dev C++ compiler

getch library function works in dev c++ compiler, also note that it doesn't support all functions of conio.h as turbo c does.

getchar in c

#include<stdio.h>
 
main()
{
   int c;
 
   c = getchar();
 
   putchar(c);
 
   return 0;
}
Common use of getch is that you can view the output (if any) of your program without having to open the output window if you are using turbo c compiler or if you are not running your program from command prompt.