Saturday, 15 October 2011

Data Types in C Language


A programming language is proposed to help programmer to process certain kinds of data and to
provide useful output. The task of data processing is accomplished by executing series of commands
called program. A program usually contains different types of data types (integer, float, character
etc.) and need to store the values being used in the program. C language is rich of data types. A C
programmer has to employ proper data type as per his requirements.
C has different data types for different types of data and can be broadly classified as:
1. Primary Data Types
2. Secondary Data Types




Primary Data Types:

Integer Data Types:

Integers are whole numbers with a range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767
(that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number.
To control the range of numbers and storage space, C has three classes of integer storage namely
short int, int and long int. All three data types have signed and unsigned forms. A short
int requires half the amount of storage than normal integer. Unlike signed integer, unsigned
integers are always positive and use all the bits for the magnitude of the number. Therefore, the
range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer
range of values and it occupies 4 bytes of storage space.

Syntax:


int <variable name>;
int num1;
short int num2;
long int num3;

Example: 5, 6, 100, 2500.


Integer Data Type Memory Allocation:





Floating Point Data Types:


The float data type is used to store fractional numbers (real numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float. When the accuracy of the floating point
number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision
further we can use long double which occupies 10 bytes of memory space.


Syntax :



float <variable name>;
float num1;
double num2;
long double num3;


Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation :



Character Data Type:


Character type variable can hold a single character and are declared by using the keyword char. As
there are singed and unsigned int (either short or long), in the same way there are signed and
unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have
values between 0 and 255, signed characters have values from –128 to 127.


Syntax:


char <variable name>;
char ch = ‘a’;


Example: a, b, g, S, j.



Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case of integer
and float. The void data type is usually used with function to specify its type.


Program to print Reverse Triangle


//print the reverse triangle


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


void main()
{
   int i, n;
cout << "Enter the value of n : ";
   cin >> n;
   cout << "\n\n";
   for (i = 0; i < n; i++)
   {
     for (int j = i; j < n; j++)
        cout << "* ";
     cout << "\n";
   }
   getch();
}


Output :



java progarm for moving cat.

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.applet.*;
public class cat extends Applet implements Runnable
 {
  Image catpics[] = new Image[9];
  Image currentimg;
  Thread runner;
  int xpos;
  int ypos = 50;
public void init()
{
    String catsrc[] = {
 "right1.gif", "right2.gif", "stop.gif", "yawn.gif", "scratch1.gif",
 "scratch2.gif","sleep1.gif", "sleep2.gif",  "awake.gif"     
 };
 for (int i=0; i < catpics.length; i++)
 {
        catpics[i] = getImage(getDocumentBase(),catsrc[i]);
    }
}
         public void start()
   {
     if (runner == null)
     {
      runner = new Thread(this);
      runner.start();
     }
          }


  public void stop()
   {
         if (runner != null)
     {
                  runner.stop();
                  runner = null;
             }
          }
         public void run()
   {
         setBackground(Color.white);
         catrun(0, size().width / 2);
         currentimg = catpics[2];
                   repaint();
         pause(1000);
         currentimg = catpics[3];
                repaint();
                pause(1000);
                catscratch(4);
                catsleep(5);
                currentimg = catpics[8];
                repaint();
                pause(500);
                catrun(xpos, size().width + 10);
          }
       void catrun(int start, int end)
   {
         for (int i = start; i < end; i += 10)
    {
                 xpos = i;
                 if (currentimg == catpics[0])
                    currentimg = catpics[1];
                 else currentimg = catpics[0];
                 repaint();
                 pause(150);
             }
          }
      void catscratch(int numtimes)
   {
            for (int i = numtimes; i > 0; i--)
     {
                  currentimg = catpics[4];
                  repaint();
                  pause(150);
                  currentimg = catpics[5];
                  repaint();
           pause(150);
              }
         }


       void catsleep(int numtimes)
   {
            for (int i = numtimes; i > 0; i--)
     {
                  currentimg = catpics[6];
                  repaint();
                  pause(250);
                  currentimg = catpics[7];
                  repaint();
                  pause(250);
              }
   }
     
  void pause(int time)
   {
            try
     {
      Thread.sleep(time);
     }
        
     catch (InterruptedException e)
     {
     }
   }
      public void paint(Graphics g)
   {
           if (currentimg != null)
              g.drawImage(currentimg, xpos, ypos, this);
   }
 }
/*
<APPLET
CODE=cat.java
WIDTH=600
HEIGHT=100 >
</APPLET>
*/












Fig.
Output:


           

Program to generate Fibonacci Series


//Program to generate Fibonacci Series


#include <stdio.h>


void main()
{
   int OldNum, NewNum, FibNum, MaxNum;


   printf("Generate Fibonacci Numbers till what number? ");
   scanf("%d", &MaxNum);


   OldNum=0;
   NewNum=1;
   FibNum = OldNum + NewNum;


   printf("%d, %d, %d, ", OldNum, NewNum, FibNum);


   for( ; ;)
   {
      OldNum = NewNum;
      NewNum = FibNum;
      FibNum = OldNum + NewNum;
      if(FibNum > MaxNum)
      {
         printf(" ");
         exit(1);
      }
      printf("%d, ", FibNum);
   }
}

Source code for conversion of numbers to letter


//convertion of number to letters


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char tens[15][15]={{""},{""},{"Twenty "},{"Thirty "},{"Fourty "},{"Fifty
"},{"Sisty "},{"Seventy "},{"Eighty "},{"Ninty "}};
char one[25][15]={{""},{"One "},{"Two "},{"Three "},{"Four "},{"Five
"},{"Six "},{"Seven "},{"Eight "},{"Nine "},{"Ten "},{"Eleven "},{"Twelve
"},{"Thirteen "},{"Fourteen "},{"Fifteen "},{"Sisteen "},{"Seventeen
"},{"Eighteen "},{"Nineteen "}};
char out[150];
int n[10]={0},i,temp1=0,temp;
long int num,f;


void convert(int i)
{
if(i==7)
{
    strcat(out,one[n[i]]);
    strcat(out,"Crore ");
}
if(i==6||i==4||i==1)
{
    if(n[i]==1)
      temp1=n[i]*10;
    if(i==1&&n[0]!=0&&f>1)
      strcat(out," And ");
    strcat(out,tens[n[i]]);
}
if((i==5||i==3||i==0||i==2))
{
    if(temp1!=0)
    {
        temp1+=n[i];
        if(i==0&&n[i+1]!=0&&n[i+2]==0&&f>1)
              strcat(out," And ");
        strcat(out,one[temp1]);
    }
    else
    {
        if(i==0&&n[i+1]!=0&&n[i+2]==0&&f>1)
              strcat(out," And ");
        strcat(out,one[n[i]]);
    }
    if(n[i]!=0||temp1!=0||n[i+1]!=0)
      switch(i)
      {        
           case 5:strcat(out,"Lakh ");break;
           case 3:strcat(out,"Thousand ");break;
           case 2:strcat(out,"Hundred ");
           if(n[i]==0)
              strcat(out," And ");
      }
      temp1=0;
  }
}

Sample source code for Binary Search


//Binary search [int array]


#include <stdio.h>
#define TRUE  0
#define FALSE 1


 int main(void) {
 int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 int left = 0;
 int right = 10;
 int middle = 0;
 int number = 0;
 int bsearch = FALSE;
 int i = 0;


 printf("ARRAY: ");
 for(i = 1; i <= 10; i++)
  printf("[%d] ", i);


 printf("\nSearch for Number: ");
 scanf("%d", &number);


 while(bsearch == FALSE && left <= right) {
  middle = (left + right) / 2;


  if(number == array[middle]) {
   bsearch = TRUE;
   printf("** Number Found **\n");
  } else {
   if(number < array[middle]) right = middle - 1;
   if(number > array[middle]) left = middle + 1;
  }
 }


 if(bsearch == FALSE)
  printf("-- Number Not found --\n");


 return 0;
}

Friday, 14 October 2011

Program to show the amazing falling character in a Matrix


//To show the falling characters in a matrix


#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <stdio.h>


using namespace std;


int main(int argc, char *argv[])
{
    
int a;
string array[105]={"A","B","C","D"," ","E","F","G"," ","H","I","J","K","L","M"," ","N","O","P","Q","R","S"," ","T","U","V","W","X","Y"," ","Z","1","2","3"," ","4","7"," ","9","0","~"," ","@","#","$","^","$"," "," "," "," ", " ", "*",":",";","?","|","#","#","$","$","$","$","?","?","?","?","@","@","0","0","0","0","0","0","0","0","0","1","1","1","1","1","1","0","0","0","0","0","1","1","1","1"};
system("TITLE The Matrix");
system("color 0A");
while(1)
{
Sleep(25);
for(int i=0; i < 26; i++)
{
a = rand()%90;
cout << "" << array [a];
cout << "  ";
}
cout << endl;
}
  system("PAUSE");
    return 0;
}







Program to print a triangle

// Program to print a triangle 



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


main()
{
   int n,m;
   cout << "Enter the value of n : ";
   cin >> n;
   m = (2*n) - 1;
   for (int i = 0; i < m; i++)
   {
      for (int j = 0; j <= i; j++)
      {
      cout << " * ";
      }
      cout << "\n";
   }


   getch();
}


Output :



Program to count the Vowels in a given string


//this program counts the vowels in a string


import java.util.*;
class CountVowels
{
  public static void main(String args[])
{
Scanner input=new Scanner(System.in);
System.out.print("Enter String: ");
String st = input.nextLine();
int count = 0; 
for (int i = 0; i < st.length(); i++) 
{
char c = st.charAt(i);
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u')
{
count++;
}
}
System.out.println("There are" + " " + count + " " + "vowels in this string.");
}
}

Program to Multiplying Two Matrixes


   // *****MULTIPLICATION of Two Matrixes*****//


#include<stdio.h>
#include<conio.h>
void main()
{
    int i,j,sum,a[10][10],b[10][10],c[10][10],m,n,k=0;
    clrscr();


    printf("       *** MULTIPLICATION OF TWO MATRIXES ***");
    printf("\nEnter the no. of rows & coloumns :\n");
    scanf("%d%d",&m,&n);
    if(m!=n)
        printf("\nEnter The same no. of rows & coloumns !");
    else
    {
        printf("Enter the elements of 1st matrix :\n");
        for(i=0;i<m;i++)
        {
           for(j=0;j<n;j++)
           scanf("%d",&a[i][j]);
        }
        printf("Enter the elements of 2nd matrix :\n");
        for(i=0;i<m;i++)
        {
           for(j=0;j<n;j++)
           scanf("%d",&b[i][j]);
        }
    
     while(k<n)
     {
       sum=0;
       for(i=0;i<m;i++)
       {
     for (j=0;j<n;j++)
     {
       for(k=0;k<n;k++)
       sum=sum+a[i][k]*b[k][j];
       c[i][j]=sum;
       sum=0;
     }
       }
     }
     printf("Result- Multipliccation of two Matrixes :\n");
     for(i=0;i<m;i++)
     {
       for(j=0;j<n;j++)
       printf("%d\t",c[i][j]);
       {
     printf("\n");
       }
     }
   
     printf("\nThanks ! For using my Program.");
     getch();
  }
}


output :

Program to Reverse a String


import java.util.*;

class ReverseString
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);

      System.out.println("Enter a string to reverse - ");
      original = in.nextLine();
      int length = original.length();


      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);

      System.out.println("Reverse of entered string is : "+ reverse);
   }
}

Source code to print a Diamond


// Program to print a diamond shape


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


main()
{
  int i,j,k,s,n,m;
  clrscr();
  cout << "Enter the value of m: ";
  cin >> m;
  n = (2*m)-1;
  for(i = 1, s = n; i <= n; i++,s--)
  {
  for(k = 1; k < s; k++)
    cout << " ";
    for(j = 1; j <= i; j++)
      {
    cout << "* ";
      }
      cout << "\n";
  }


 for(i = (n-1), s = 1; i >= 1; i--, s++)
 {
  for(k = 1; k <= s; k++)
    cout << " ";
    for(j = 1; j <= i; j++)
    {
    cout << "* ";
    }
    cout << "\n";
  }
  getch();
}


Output :



Program to print the list of ASCII codes


/**********************************************************************************/
/*  Program that print the single character list of ASCII codes from ! to  ~ */
/**********************************************************************************/

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

void main()
{
int i;
   char c = ' ';
   for (i = 0; i < 95; i++ )
   {
    printf("\n\n ASCII code of ' %c ' is %d",c++, c );
   }
   getch();
}

Source code for Quick Sort


/********************************************************\
 * ***************                       ************** *
 * *             *       QUICK SORT      *            * *
 * ***************                       ************** *
/********************************************************/


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


int partition(int a[], int p, int r)
{
    int x, i, j, temp;
    x = a[r];
    i = p-1;
    for(j = p; j <= r-1; j++)
    {
       if(a[j] <= x)
       {
        i = i+1;
temp = a[i];
a[i] = a[j];
                a[j] = temp;
       }
    }
    temp = a[i+1];
    a[i+1] = a[r];
    a[r] = temp;
    return (i+1);
}




void quick_sort(int a[], int p, int r)
{
   int q;
   if(p < r)
   {
       q = partition(a, p, r);
       quick_sort(a, p, q-1);
       quick_sort(a, q+1, r);
   }
}


void main()
{
int i, n, p = 0;
        int* a;
  clrscr();
  cout << "Enter  the no of elements: ";
  cin  >> n;
        a = (int*) malloc(sizeof(int)*n);
  cout << "\nEnter the elements:\n\n";
  for(i = 0; i < n; i++)
  {
    cin >> a[i];
  }
  quick_sort(a, p, n);
  cout << "\nSorted array is: ";
  for(i = 0;i < n; i++)
  {
    cout << a[i] << " ";
  }
   getch();
}


Output :