Wednesday 21 December 2011

What are Pointers?

A pointer provides a way of accessing a variable without referring to the variable directly.
The mechanism used for this is the address of variable. The address act as an intermediate between the variable  and the program accessing it.
Let's have a look at the following example:


#include<stdio.h>
#include<conio.h>
void main()
{
   int *p, q;   //pointer variable always initialize with an *
     q = 100;   //assigning value to q 
     p = &q;    //inserting the address of q into p
       printf("%d",*p);  //see the description below
   getch();     //exit on key press                                                         
}

In the above program, the value of q (i.e. 100) is shown through the pointer variable p (i.e. *p). You can easily see in the picture above. First, store 100 the q variable and then the address of q (i.e. 1312) is given to pointer variable p and at last the value of q is print through pointer variable (*p).

If you still have any problem or confusion, you can contact me... 

Saturday 17 December 2011

How to display a colorful animated string/phrase


#include<graphics.h>
#include<conio.h>
#include<stdio.h>
#include<dos.h>      // for delay() function


void main(void)
{
    int driver=DETECT, mode;
    int i;    //for loop
    initgraph(&driver, &mode, "c:\\TC\\bgi" );
    textcolor(BLACK);
    for(i=0;i<=400;i++)
    {
    clrscr();
    setcolor(i/15);     //set text/string color
    outtextxy(20+i,150,"**C Language Codes**");  //see the description below
    delay(30);       //slow down the loop
    }
    getch();
    closegraph();
}


What is outtextxy(); ?


It is a built-in function defined in the header file "graphics.h". This function used to display graphical string. The general syntax is as follows:
outtextxy(x-coordinate, y-coordinate, "String to display"); 


In the above program, outtextxy() function is put into for loop to make the text animated. As you can see that variable i is written with the x-coordinate whereas, the y-coordinate remains constant which means the text will move towards left to right on the screen.


If you still have any question, you can ask me freely... 



Draw a colorful Circle


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

void main(void)
{
    int driver=DETECT, mode;
    int xc1=320, yc1=240;


       initgraph(&driver, &mode, "c:\\TC\\bgi" );
         setcolor(7);                     //edge color
         setfillstyle(SOLID_FILL,GREEN);  // fill inside the circle
         circle(xc1,yc1,100);             // create a circle
         floodfill(xc1,yc1,7);            // flood color
     getch();
    closegraph();
}


Output:
















If you have any question, you can ask me freely...

Friday 18 November 2011

How to Initialize Graphics mode in C language

/*Header Files*/
#include<stdio.h>                  //for input/output purpose
#include<conio.h>                 //for getch() function
#include<graphics.h>            //for graphics functions
void main()
{
         int driver=DETECT, mode;                               //auto detect the driver
         int x=320, y=240, radius=100;                            // initialization
           initgraph(&driver , &mode , "c:\\tc\\bgi");  // all necessary graphics files in BGI folder
                  circle(x , y, radius);                                            //create a circle
         getch();                                                          // waits for key press
         closgraph();                                                    //close graphics mode
}

The above program will give the following output:


Wednesday 17 August 2011

Program to identify the prime number


Code:
#include<stdio.h>
#include<conio.h>
void main()
{
      int num,flag=0,a;
            printf("Enter an integer: ");
            scanf("%d",&num);
      //Logic for prime number
            if(num==2)
                  printf("%d is Prime Number.",num); 
            else
            {
                  for(a=2;a<num;a++)
                  {
                        if(num%a==0)
                              flag=1;
                  }
            }
            if(flag==1)
                  printf("%d is not a Prime Number.",num);
            else
                  printf("%d is Prime Number.",num);
      getch();

}

Result:

Enter an integer: 8
8 is not a Prime Number.

If you have any confusion about that program, contact me freely :)


Interchanging two variables without using the third one


Using less variables is a sign of good programming. Here's the example program to interchanging the values of two variables without using third variable.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
//Initialization
  int var1,var2; 
    printf("Enter two integers\n");
//Taking input from user
      printf("a = ");
      scanf("%d",&var1);
      printf("b = ");
      scanf("%d",&var2);
   var1=var1+var2;
   var2=var1-var2;
   var1=var1-var2;
    printf("a = %d\n",var1);
    printf("b = %d\n",var2);
  getch();

}

Result:

Enter two integers
a = 5
b = 11
a = 11
b = 5

Thursday 16 June 2011

An Array of String (Security)

#define MAX 5
#define LEN 40


void main(void)
{
 int dex;
 int enter=0;
 char name[40];
 static char list[MAX][LEN]={ "Muzammil", "Nigel", "Katrina",
                              "Alistair" };
 printf("Enter your name:"):
 gets(name);
 for(dex=0;dex<MAX;dex++)
  if(strcmp(&list[dex][0],name)==0)
   enter = 1;
 if(enter==1)
   printf("You may enter, oh honored one.");
 else
   printf("Guards! Remove this person!");
 }


Output:
There are two possible outcomes when you interact with this program. Either your name is on the list:


Enter your name: Muzammil
You may enter, oh honored one.


or it isn't:


Enter your name: George
Guards! Remove this person!

The String I/O Functions gets() and puts()

void main(void)
{
 char name[81];


 puts("Enter your name: ");
 gets(name);
 puts("Greetings, ");
 puts(name);
}


Output:


Enter your name: 
Muzammil Versiani
Greetings, 
Muzammil Versiani

Thursday 9 June 2011

Switch Case in C


    The basic form of a switch statement is:
    switch (variable) { case expression1: do something 1; break; case expression2: do something 2; break; .... default: do default processing; }
     In the c program below, if you enter 5 , it will display you entered 5, else if the condition fails it will display the default , that is "i don't know what u entered". The break statement terminates the loop.
    Another Example of Switch Case Program:
    switch( marks )      {         case 'A' : printf( "A++" );                    break;         case 'B' : printf( "A+" );            break; case 'C' : printf( "A" );            break;         case 'D' : printf( "B" );            break; case 'F' : printf( "C" );               break; default  : printf( "YOU FAILED" );                    break; }
    The keyword break must be included at the end of each case statement. The default clause is optional
    We also have a continue statement which is used with switch case.
    A continue statement causes a jump to the loop-continuation portion of the smallest enclosing iteration statement; that is, to the end of the loop body.

Switch Case in C


    The basic form of a switch statement is:
    switch (variable) { case expression1: do something 1; break; case expression2: do something 2; break; .... default: do default processing; }
     In the c program below, if you enter 5 , it will display you entered 5, else if the condition fails it will display the default , that is "i don't know what u entered". The break statement terminates the loop.
    Another Example of Switch Case Program:
    switch( marks )      {         case 'A' : printf( "A++" );                    break;         case 'B' : printf( "A+" );            break; case 'C' : printf( "A" );            break;         case 'D' : printf( "B" );            break; case 'F' : printf( "C" );               break; default  : printf( "YOU FAILED" );                    break; }
    The keyword break must be included at the end of each case statement. The default clause is optional
    We also have a continue statement which is used with switch case.
    A continue statement causes a jump to the loop-continuation portion of the smallest enclosing iteration statement; that is, to the end of the loop body.

Wednesday 1 June 2011

String Variables

void main(void)
{
 char name[81];
 printf("Enter your Name: ");
 scanf("%s",name);
 printf("Welcome!, %s",name);
 getch();
}


Output:


Enter your Name: Muzammil
Welcome!, Muzammil




If you have any question, you can ask me freely!

Sorting an Array (increasing order)

#define MAXSIZE 20
void sort(int[],int);


void main (void)
{
 static int list[MAXSIZE];
 int size=0;
 int dex;
 do
  {
   printf("Type Number: ");
   scanf("%d",&list[size]);
  } 
 while(list[size++] != 0);
 sort(list,--size);
 for(dex=0;dex<size;dex++)
  printf("%d\n",list[dex]);


}
void sort(int[list],int size)
 {
  int out,in,temp;
  for(out=0;out<size-1;out++)
   for(in=out+1;in<size;in++)
    if(list[out]>list[in])
      {
       temp = list[in];
       list[in] = list[out];
       list[out] = temp;
      }
}


Output:
Type Number: 46
Type Number: 25
Type Number: 73
Type Number: 58
Type Number: 33
Type Number: 18
Type Number: 0
18
25
33
46
58
73


If you have any question, you ask me freely!

Tuesday 31 May 2011

Which Number is Largest? / Array

#define MAXSIZE 20
int max(int[], int);
void main()
{
 int list[MAXSIZE];
 int size=0;
 int num;
 do
  {
   printf("Type number: ");
   scanf("%d",list[size]);
  }
 while(list[size++] != 0);
 num=max(list,size-1);
 printf("Largest Number is %d",num);
}
int max(int list[],int size)
{
  int dex,max;
  max = list[0];
  for(dex=1;dex<size;dex++)
   if(max < list[dex])
    max = list[dex];
  return(max);
}


Output:


Type Number: 42
Type Number: 1
Type Number: 64
Type Number: 33
Type Number: 27
Type Number: 0 
Largest Number is 64



Monday 30 May 2011

Arrays

If you have collection of similar data elements, you may find it inconvenient to give each one a unique variable name. For instance, suppose you wanted to find the average temperature for a particular week. If each day's temperature had a unique variable name, you would end up reading in each value separately like this:


printf("Enter Sunday Temperature: ");   
scanf("%d",&suntmp);
printf("Enter Monday Temperature: ");
scanf("%d",&montmp);
---------------


and so on for each day of the week, with an expression for the average such as this:


(suntmp+montmp+tuetmp+wedtmp+thutmp+fritmp+sattmp)/7


This is on altogether unwieldy business, especially if you want to average the temperature for a month or a year.
 Clearly we need a convenient way to refer to such collections of similar data elements. The array fills the bill. It provides a way to refer to individual items in a collection by using the same variable name, but differing subscripts, or numbers. Let's see how we'd solve our problem of averaging the temperature for a week using arrays:


void main()
{
 int temper[7];
 int day,sum;


 for(day=0;day<7;day++)
 {
  printf("Enter Temperature for day %d: ",day);
  scanf("%d",&temper[day]);
 }

 sum=0;
 for(day=0;day<7;day++)
  sum+=temper[day];
 printf("Average is %d.",sum/7);





This program reads in seven temperatures, stores them in an array and then, to calculate an average temperature, reads them back out of the array, adding them together, and divide by 7. Here's a result:


Enter Temperature for day 0: 74
Enter Temperature for day 1: 76
Enter Temperature for day 2: 77
Enter Temperature for day 3: 77
Enter Temperature for day 4: 64
Enter Temperature for day 5: 66
Enter Temperature for day 6: 69
Average is 71.


If you have any question, you can ask me freely!

Friday 27 May 2011

Functions that Return a Value

#include<stdio.h>
#include<conio.h>
char getlc(void);


void main(void)
{
 char chlc;
 printf("Type 'a' for first selection, 'b' for second: ");
 chlc=getche();
 switch(chlc)
  {
   case'a':
   printf("\nYou typed an 'a'.");
   break;
   case'b':
   printf("\nYou typed a 'b'.");
   break;
   default:
   printf("\nYou chose a nonexistent selection.");
  }
}
char getlc(void)
{
 char ch;
 ch=getche();
 if(ch>64&&ch<91)
 ch=ch+32;
 return(ch);
}


Output:
Type 'a' for first selection, 'b' for second: a
You typed an 'a'.





Type 'a' for first selection, 'b' for second: A
You typed an 'a'.


Type 'a' for first selection, 'b' for second: c
You chose a nonexistent selection.

Thursday 26 May 2011

Finding LCM and GCD

Finding LCM and GCD



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


void main()
{
  int a[20],n,i,j,c,max,min;
  unsigned long prod;
  clrscr();
  printf("Enter the no. of entries: ");
  scanf("%d",&n);
  printf("Enter the entries:
");
  for(i=0;i<n;i++)
  {
    scanf("%d",&c);
    if(c>0)
      a[i]=c;
    else
    {
      printf("Invalid Entry");
      return;
    }
  }


  max=a[0];
  for(i=0;i<n;i++)
    if(a[i]>=max)
      max=a[i];
  min=a[0];
  for(i=0;i<n;i++)
    if(a[i]<min)
      min=a[i];


  for(i=0,prod=1;i<n;i++)
    prod=prod*a[i];


  for(i=max;i<=prod;i+=max)
  {


    c=0;
    for(j=0;j<n;j++)
      if(i%a[j]==0)
c+=1;
    if(c==n)
    {
      printf("The LCM of the nos: %d
",i);
      break;
    }
  }


  for(i=min;i>0;i--)
  {
    if (min%i==0)
    {
      c=0;
      for(j=0;j<n;j++)
if(a[j]%i==0)
  c+=1;
    }
    if(c==n)
    {
      printf("The GCD of the nos: %d",i);
      break;
    }
  }
  getch();
}

Calculate Area of a Polygon


Program to calculate Area of a Polygon






#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_VERT 50
enum {x, y};
typedef struct triangle {
    double v1[2];
    double v2[2];
    double v3[2];
} triangle;
double area(triangle a);
double perimeter(double *vertices, int size);
double side(double *p1, double *p2);


int main(void)
{
  int n, idx;
  int triangles;
  int index;
  int xycount;
  double xy;
  double triangle_area;
  double polygon_area;
  double perim;
  double polygon_vertices[MAX_VERT] = {0.0};
  triangle a;
  FILE *data;


  xycount = 0;
  polygon_area = 0;
  if((data = fopen("pvert.txt", "r")) == NULL)
  {
    fprintf(stderr, "can't open data file
");
    exit(EXIT_FAILURE);
  }


  /* Read x-y coordinates of the vertices
     of the polygon from a file. */
  while(fscanf(data, "%lf", &xy) == 1)
    polygon_vertices[xycount++] = xy;
  fclose(data);
  idx = 0;
  /* triangles in polygon = vertices - 2 */
  triangles = (xycount / 2) - 2;
  putchar('
');


  for(index = 2, idx = 0; idx < triangles; index += 2, ++idx)
  {
  /* Load vertices of a triangle into struct.
     1st vertex of the polygon will be the 1st
     vertex of each triangle. index holds the
     starting index of each consecutive set of
     triangle vertices after the 1st. */
    a.v1[x] = polygon_vertices[0];
    a.v1[y] = polygon_vertices[1];
    a.v2[x] = polygon_vertices[index+0];
    a.v2[y] = polygon_vertices[index+1];
    a.v3[x] = polygon_vertices[index+2];
    a.v3[y] = polygon_vertices[index+3];


    /* calculate the area of the triangle */
    triangle_area = area(a);
    printf("area of triangle = %.2f
", triangle_area);


    /* add triangle area to polygon area */
    polygon_area += triangle_area;
  }
  printf("
area of polygon = %.2f
", polygon_area);


  /* calculate the perimeter of the polygon */
  perim = perimeter(polygon_vertices, xycount);
  printf("perimeter of polygon = %.2f
", perim);


  return 0;
}


/* calculate triangle area with Heron's formula */
double area(triangle a)
{
  double s1, s2, s3, S, area;


  s1 = side(a.v1, a.v2);
  s2 = side(a.v2, a.v3);
  s3 = side(a.v3, a.v1);
  S = (s1 + s2 + s3) / 2;
  area = sqrt(S*(S - s1)*(S - s2)*(S - s3));


  return area;
}


/* calculate polygon perimeter */
double perimeter(double *vertices, int size)
{
  int idx, jdx;
  double p1[2], p2[2], pfirst[2], plast[2];
  double perimeter;


  perimeter = 0.0;
  /* 1st vertex of the polygon */
  pfirst[x] = vertices[0];
  pfirst[y] = vertices[1];
  /* last vertex of polygon */
  plast[x] = vertices[size-2];
  plast[y] = vertices[size-1];
  /* calculate perimeter minus last side */
  for(idx = 0; idx <= size-3; idx += 2)
  {
    for(jdx = 0; jdx < 4; ++jdx)
    {
      p1[x] = vertices[idx];
      p1[y] = vertices[idx+1];
      p2[x] = vertices[idx+2];
      p2[y] = vertices[idx+3];
    }
    perimeter += side(p1, p2);
  }
  /* add last side */
  perimeter += side(plast, pfirst);


  return perimeter;
}


/* calculate length of side */
double side(double *p1, double *p2)
{
  double s1, s2, s3;


  s1 = (p1[x] - p2[x]);
  s2 = (p1[y] - p2[y]);
  s3 = (s1 * s1) + (s2 * s2);


  return sqrt(s3);
}