Tuesday 24 January 2017

Program for single linked list

To store a group of data of same data type array data structure is used. But the problem with arrays is that the size of the array is fixed and it supports static memory allocation which may result in wastage of memory location. Another problem with array is that contiguous memory locations must be available.
An alternate data structure to arrays is linked list which follows dynamic memory allocation and elements need not be in contiguous memory location. To keep track of the next element, the address of the next element is stored in each node of the linked list. 
The following c program shows how to create a linked list and insert or delete elements in the linked list.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
  int element;
  struct node *next;
}*list=NULL,*P;

struct node *find(int);
struct node *findprevious(int);
void insert(int X);
void delete(int X);
void display( );

void main( )
{
  int data,ch;
  
  clrscr( );
  printf("\n1.Insert\t2.Delete\t3.Display\t4.Exit");
  do
  {
    printf("\nEnter your choice:");
    scanf("%d",&ch);
    switch(ch)
    {
      case 1:
             printf("\nEnter the element to insert:");
             scanf("%d",&data);
             insert(data);
    break;
case 2:
    printf("\nEnter the element to delete:");
    scanf("%d",&data);
    delete(data);
    break;
case 3:
    display();
    break;
case 4:
    exit(0);
    }
  }while(ch<4);
getch();
}

void insert(int X)
{
  struct node *newnode;
  int pos;
  newnode=malloc(sizeof(struct node));
  newnode->element=X;
  if(list->next==NULL)
  {
    list->next=newnode;
    newnode->next=NULL;
  }
  else
  {
    printf("\nEnter the value after which the element to be inserted:");
    scanf("%d",&pos);
    P=find(pos);
    newnode->next=P->next;
    P->next=newnode;
   }
}

struct node *find(int s)
{
  P=list->next;
  while(P!=NULL&&P->element!=s)
  {
    P=P->next;
  }
  return P;
}

void delete(int X)
{
  struct node *temp;
  temp=malloc(sizeof(struct node));
  P=findprevious(X);
  if(P->next!=NULL)
  {
    temp=P->next;
    P->next=temp->next;
    printf("\nThe deleted element is %d",temp->element);
    free(temp);
  }
  else
  {
    printf("Element not found in the list");
  } 
}

struct node *findprevious(int s)
{
  P=list;
  while(P->next!=NULL && P->next->element!=s)
  {
    P=P->next;
  }
  return P;
}

void display()
{
  if(list->next==NULL)
  {
    printf("List is empty");
  }
  else
  {
    P=list->next;
    printf("\nThe contents of the list are:");
    while(P!=NULL)
    {
      printf("%d->",P->element);
      P=P->next;
     }
     printf("NULL");
  }
}

/*
OUTPUT
--------

1.Insert        2.Delete        3.Display       4.Exit
Enter your choice:1

Enter the element to insert:1

Enter your choice:1

Enter the element to insert:2

Enter the value after which the element to be inserted:1

Enter your choice:1

Enter the element to insert:3

Enter the value after which the element to be inserted:2

Enter your choice:3

The contents of the list are:1->2->3->NULL
Enter your choice:4

*/

Monday 16 January 2017

Calling functions with varying number of arguments

The number of arguments in a function call need not be same every time a function is called. In C language it is possible to call a function with varying number of arguments.

<stdarg.h> header file defines three functions va_arg, va_start and va_end to work with the varying number of arguments in a function call. It also declares a data-type called va_list.

The following C program shows how to call a function min() with varying list of arguments. The first argument in the list is the number of arguments in the function call.

//Program to find minimum number in a list of arguments
#include<stdio.h>
#include<stdarg.h>
#include<conio.h>
#include<limits.h>

int min(int cnt,...)
{
  va_list valist;
  int i,n,min=INT_MAX;

  va_start(valist,cnt);
  printf("\nArguments in the function call\n");
  for(i=0;i<cnt;i++)
  {
      n=va_arg(valist,int);
      printf("%d  ",n);
      if (n<min)
    min=n;
  }

  va_end(valist);
  return min;
}
main()
{
 clrscr();
 printf("\nThe smallest number in the list is %d\n",min(6,90,35,2,68,108,18));
 printf("\nThe smallest number in the list is %d\n",min(10,6,5,7,-5,100,30,25,0,1,10));
 getch();
}

/*
OUTPUT
-------

Arguments in the function call                                                
90  35  2  68  108  18                                                        
The smallest number in the list is 2                                          
                                                                              
Arguments in the function call                                                
6  5  7  -5  100  30  25  0  1  10                                            
The smallest number in the list is -5                                         
*/

Calling functions using pointer

Pointers in C language makes it unique and offers effective programming capabilities. Using pointers to call functions in C is the best way to call a function dynamically.


//C program to call functions using pointers
#include<stdio.h>
int add(int,int); //function prototype
int sub(int,int);
main()
{
 int a,b;
 int (*ptr1)(int,int)=add;    //declaring pointer to a function and assigning the address of add function
 int (*ptr2)(int,int);

 clrscr();
 ptr2=sub;          //assigning the address of function sub
 printf("\nEnter two numbers to add\n");
 scanf("%d%d",&a,&b);

 printf("\ncalling function using pointer\n");
 printf("-----------------------------------\n");
 (*ptr1)(a,b);         //calling function using ptr1 variable
 ptr2(a,b);             //another way to call function using pointer
 getch();
}
int add(int a,int b)
{
 printf("The result of addition is %d\n",a+b);
}
int sub(int a,int b)
{
  printf("The result of subtraction is %d\n",a-b);
}

/*
OUTPUT
---------
Enter two numbers to add
5
6

calling function using pointer
-----------------------------------
The result of addition is 11
The result of subtraction is -1
*/

Thursday 12 January 2017

Create your own data type


Programmer defined data types are one of the most powerful features offered by any programming language. They are easy to handle in situations of unforeseen changes.

Following is one such situation which explains the benefit of using user defined data types.

In C programming language, user can define their own data types using typedef


               typedef float coordinate;

Here, coordinate is a user defined data type which can be used to declare variables of type float as shown in the below function;

               function1( )
               { 
                   coordinate n1,n2;
                   coordinate result;
                     ........................
                }

Now suppose we want to change the data type of all float variables to double, it is enough to change it in typedef as follows:

                typedef double coordinate;

Hence it is advisable to create user defined data types whenever it is possible for the following reasons:
  • To make modification easier
  • To avoid excessive information distribution
  • To increase reliability
  • To make-up for programming language weaknesses

Wednesday 11 January 2017

Passing a function as an argument to a function

In C, while calling a function to carry out a task, usually the data for the function is sent as arguments. But it is also possible to send a function itself as an argument. The following program defines two functions add( ) and sub( ) which are passed as an argument to another function.

//C program to pass function as an argument
#include<stdio.h>
int add(int,int);
int sub(int,int);
void f_calling_f(int,int,int (*)(int,int));
void main ()
{
  clrscr();
  printf("Passing function to function\n");
  f_calling_f(10,20,add);
  f_calling_f(10,20,sub);
  getch();
}
void f_calling_f(int a,int b,int (*f)(int,int))
{
   f(a,b);
}
int add(int a,int b)
{
   printf("\nThe result of addition of %d and %d is %d\t",a,b,a+b);
}
int sub(int a,int b)
{
   printf("\nThe result of subtraction of %d and %d is %d\t",a,b,a-b);
}


/*
OUTPUT
------------
Passing function to function
                                                                                
The result of addition of 10 and 20 is 30                                       
The result of subtraction of 10 and 20 is -10
*/                                                             

C program to process result of students using structure

Structure is a complex data type used to group related data of different data types. Usually structure is used to store records.To process more than one record, an array of structures is created. The following program process the result of students using array of structures.

//Program to process student result
#include<stdio.h>
#include<conio.h>

struct student
{
 int stdno,m[20],total;
 float avg;
 char name[10];
}s[10];
main()
{
 int i,j,n,p,sum=0;

 clrscr();
 printf("Enter the students details\n");
 printf("Enter the total number of students for whom the details are required\t");
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
  printf("Enter student %d details\n",i+1);
  printf("Enter the students register number:\t");
  scanf("%d",&s[i].stdno);
  printf("Enter the name of the student:\t");
  scanf("%s",s[i].name);
  printf("Enter the total number of subjects;\t");
  scanf("%d",&p);
  sum=0;
  for(j=0;j<p;j++)
  {
    printf("Enter the marks of subject %d\n",j+1);
    scanf("%d",&s[i].m[j]);
    sum=sum+s[i].m[j];
  }
  s[i].total=sum;
  s[i].avg=s[i].total/j;
 }
 for(i=0;i<n;i++)
 {
   printf("\nStudent %d details",i+1);
   printf("\n--------------------------");
   printf("\nName of the student:%s  ",s[i].name);
   printf("\nRegister number :%d  ",s[i].stdno);
   for(j=0;j<p;j++)
      printf("\nSubject[%d] Mark = %d\t",j+1,s[i].m[j]);
   printf("\nTotal marks;%d  ",s[i].total);
   printf("\nAverage marks:%f\n",s[i].avg);
   getch();
  }
}

/*
OUTPUT
-------
Enter the students details
Enter the total number of students for whom the details are required    2
Enter student 1 details
Enter the students register number:     1
Enter the name of the student:  ss                                            
Enter the total number of subjects;     3                                      
Enter the marks of subject 1                                                  
1                                                                              
Enter the marks of subject 2                                                  
2                                                                              
Enter the marks of subject 3
3

Enter student 2 details
Enter the students register number:     2
Enter the name of the student:  sa
Enter the total number of subjects;     3
Enter the marks of subject 1
1
Enter the marks of subject 2
1
Enter the marks of subject 3
1

Student 1 details
--------------------------
Name of the student:ss
Register number :1
Subject[1] Mark = 1
Subject[2] Mark = 2
Subject[3] Mark = 3
Total marks;6
Average marks:2.000000

Student 2 details
--------------------------
Name of the student:sa
Register number :2
Subject[1] Mark = 1
Subject[2] Mark = 1
Subject[3] Mark = 1
Total marks;3
Average marks:1.000000
*/





Thursday 5 January 2017

C program to print Floyd's triangle

Floyd's triangle is a right-angled triangular array of natural numbers. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner:


//Program to print Floyd's triangle
#include<stdio.h>
#include<conio.h>
main()
{
 int i,j,row,t=1;
 clrscr();
 printf("Enter the number of rows\t");
 scanf("%d",&row);
 for(i=0;i<row;i++)
 {
  for(j=0;j<=i;j++)
  {
    if (t<10)
       printf("%d  ",t);
    else
       printf("%d ",t);
     t++;
   }
   printf("\n");
  }

 getch();
}

/*
OUTPUT
--------
Enter the number of rows        10
1
2  3
4  5  6
7  8  9  10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55


*/

C program to check leap year

A leap year comes once in every four years and once in four centuries. A very common mistake most of the programmers does is forgetting to check for centuries. Most of the time students will check whether the year is divisible by 4. If the given year is a century, then we must check whether it is divisible by 400.

//Program to check for leap year
#include<stdio.h>
#include<conio.h>
main()
{
 int year,lpyr=0;
 clrscr();
 printf("Enter a year\t");
 scanf("%d",&year);
 if (year%100==0)
   {
     lpyr=year%400;
     if (lpyr==0)
     {
       printf("The year %d is a leap year\n",year);
     }
     else
       printf("%d is not a leap year\n",year);
   }
 else
   {
     lpyr=year%4;
     if (lpyr==0)
     {
       printf("%d is a leap year\n",year);
     }
     else
       printf("%d is not a leap year\n",year);
   }
 getch();
}

/*
OUTPUT
--------
Enter a year    1900
1900 is not a leap year

Enter a year    2000
The year 2000 is a leap year

Enter a year    2003
2003 is not a leap year

Enter a year    2008
2008 is a leap year
*/

Wednesday 4 January 2017

C Program to implement stack using array

Stack is a data structure used in computer programming. Recursive function call is performed with the help of stack. The elements in the stack are accessed Last In First Out (LIFO) order.

//Program to implement stack using arrays
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int sp=-1;
main()
{
  int a[SIZE],i,n,choice;
  int push(int *,int);
  int pop(int *);

  clrscr();
  do
  {
    printf("1. Push\n");
    printf("2. Pop\n");
    printf("3. Display\n");
    printf("4. Quit\n");
    printf("Enter Choice ");
    scanf("%d",&choice);
    switch (choice)
    {
      case 1: printf("Enter element to be pushed into the stack ");
     scanf("%d",&n);
     push(a,n);
     break;

      case 2: n=pop(a);
     if(n!=NULL)
printf("The element popped out from stack is %d\n",n);
     break;

      case 3: if (sp>=0)
     {
printf("Elements in the stack\n");
for(i=sp;i>=0;i--)
  printf("%d\t",a[i]);
     }
     else
     printf("Stack Empty\n");
     break;

      case 4: exit(0);
     break;

      default: printf("wrong choice\n");
   }
   printf("\nDo you want to continue? (1. Yes 2.No)\n");
   scanf("%d",&choice);
  }while (choice==1);
 getch();
}
int push(int *a,int n)
{
   if (sp<SIZE)
      a[++sp]=n;
   else
      printf("Stack Full\n");
   return 1;
}
int pop(int *a)
{
   if (sp==-1)
   {
      printf("Stack empty\n");
      return NULL;
   }
   else
    return a[sp--];
}
/*
OUTPUT
-------
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 1
Enter element to be pushed into the stack 1

Do you want to continue? (1. Yes 2.No)
1
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 1
Enter element to be pushed into the stack 2

Do you want to continue? (1. Yes 2.No)
1
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 1
Enter element to be pushed into the stack 3

Do you want to continue? (1. Yes 2.No)
1
1. Push
2. Pop
3. Display
4. Quit
Enter Choice 3
Elements in the stack
3       2       1
Do you want to continue? (1. Yes 2.No)
1

*/

Monday 2 January 2017

C Program to work with strings without string functions

This simple program shows you how to find the string length, copy a string and concatenate two strings without using built-in string functions.

//Program to manipulate strings without string functions
#include<stdio.h>
#include<conio.h>
main()
{
  char *str1,*str2;
  int i,j, choice;

  clrscr();
  printf("1. String length\n");
  printf("2. String copy\n");
  printf("3. String Concat\n");
  printf("Enter choice\n");
  scanf("%d",&choice);
  switch (choice)
  {
    case 1: printf("\nEnter string\n");
   fflush(stdin);
   gets(str1);
   for(i=0;str1[i]!='\0';i++);
   printf("The length of the string  \"%s\" is %d",str1,i);
   break;

   case 2: printf("\nEnter string to be copied\n");
  fflush(stdin);
  gets(str1);
  for(i=0;str1[i]!='\0';i++)
     str2[i]=str1[i];
     str2[i]='\0';
  printf("String1 = %s",str1);
  printf("\nThe copied string str2 = %s", str2);
  break;

   case 3: printf("\nEnter string1 and string2\n");
  fflush(stdin);
  gets(str1);
  gets(str2);
  for(i=0;str1[i]!='\0';i++);

  for(j=0;str2[j]!='\0';j++)
  str1[i++]=str2[j];
  str1[i]='\0';
  printf("\nThe concatenated string is %s",str1);
  break;

   default: printf("\nWrong choice\n");
   }

   getch();
}

/*
OUTPUT
--------
1. String length
2. String copy
3. String Concat
Enter choice
3

Enter string1 and string2
good
morning

The concatenated string is goodmorning

1. String length
2. String copy
3. String Concat
Enter choice
1

Enter string
welcome
The length of the string  "welcome" is 7

1. String length
2. String copy
3. String Concat
Enter choice
2

Enter string to be copied
welcome
String1 = welcome
The copied string str2 = welcome
*/