Monday, March 16, 2015

C Useful programs



Accessing Array Elements

#include 
#include
int main ()
{
   int n[ 10 ];
   int i,j;
   for ( i = 0; i < 10; i++ )
   {
      n[ i ] = i + 100; 
   }
      for (j = 0; j < 10; j++ )
   {
      printf("Element[%d] = %d\n", j, n[j] );
   }
    return 0;
}

C using Strings program


#include 
#include
#include 
 
int main ()
{
   char str1[12] = "Hello";
   char str2[12] = "World";
   char str3[12];
   int  len ;
   strcpy(str3, str1);
   printf("strcpy( str3, str1) :  %s\n", str3 );
   strcat( str1, str2);
   printf("strcat( str1, str2):   %s\n", str1 );
   len = strlen(str1);
   printf("strlen(str1) :  %d\n", len );
   return 0;
}

Calling Functions program
 
#include 
#include 
int max(int num1, int num2);
int main ()
{
   int a = 100;
   int b = 200;
   int ret;
   ret = max(a, b);
   printf( "Max value is : %d\n", ret );
   return 0;
}
int max(int num1, int num2) 
{
   int result;
    if (num1 > num2)
      result = num1;
   else
      result = num2;
    return result; 
}

Variable Arguments


#include 
#include
#include 
double average(int num,...)
{
    va_list valist;
    double sum = 0.0;
    int i;
    va_start(valist, num);
    for (i = 0; i < num; i++)
    {
       sum += va_arg(valist, int);
    }
     va_end(valist);
    return sum/num;
}
int main()
{
   printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
   printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}

Allocating Memory Dynamically

#include 
#include
#include 
#include 
int main()
{
   char name[100];
   char *description;
   strcpy(name, "Zara Ali");
   description = malloc( 200 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student in class 10th");
   }
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
}

Resizing and Releasing Memory

#include 
#include
#include 
#include 
int main()
{
   char name[100];
   char *description;
   strcpy(name, "Zara Ali");
   description = malloc( 30 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student.");
   }
   description = realloc( description, 100 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcat( description, "She is in class 10th");
   }
   
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
   free(description);
}

No comments:

Post a Comment