C Program of priority queue using linked list


/*Program of priority queue using linked list*/
#include<stdio.h>
#include<stdlib.h>

struct node
{
int priority;
int info;
struct node *link;
}*front=NULL;

void insert(int item, int item_priority);
int del();
void display();
int isEmpty();

main()
{
int choice,item,item_priority;
while(1)
{
printf(“1.Insert\n”);
printf(“2.Delete\n”);
printf(“3.Display\n”);
printf(“4.Quit\n”);
printf(“Enter your choice : “);
scanf(“%d”, &choice);

switch(choice)
{
case 1:
printf(“Input the item to be added in the queue : “);
scanf(“%d”,&item);
printf(“Enter its priority : “);
scanf(“%d”,&item_priority);
insert(item, item_priority);
break;
case 2:
printf(“Deleted item is %d\n”,del());
break;
case 3:
display();
break;
case 4:
exit(1);
default :
printf(“Wrong choice\n”);
}/*End of switch*/
}/*End of while*/
}/*End of main()*/

void insert(int item,int item_priority)
{
struct node *tmp,*p;

tmp=(struct node *)malloc(sizeof(struct node));
if(tmp==NULL)
{
printf(“Memory not available\n”);
return;
}
tmp->info=item;
tmp->priority=item_priority;
/*Queue is empty or item to be added has priority more than first element*/
if( isEmpty() || item_priority < front->priority )
{
tmp->link=front;
front=tmp;
}
else
{
p = front;
while( p->link!=NULL && p->link->priority<=item_priority )
p=p->link;
tmp->link=p->link;
p->link=tmp;
}
}/*End of insert()*/

int del()
{
struct node *tmp;
int item;
if( isEmpty() )
{
printf(“Queue Underflow\n”);
exit(1);
}
else
{
tmp=front;
item=tmp->info;
front=front->link;
free(tmp);
}
return item;
}/*End of del()*/

int isEmpty()
{
if( front == NULL )
return 1;
else
return 0;

}/*End of isEmpty()*/

void display()
{
struct node *ptr;
ptr=front;
if( isEmpty() )
printf(“Queue is empty\n”);
else
{    printf(“Queue is :\n”);
printf(“Priority       Item\n”);
while(ptr!=NULL)
{
printf(“%5d        %5d\n”,ptr->priority,ptr->info);
ptr=ptr->link;
}
}
}/*End of display() */

C Program of reversing a string using stack


 

/*Program of reversing a string using stack */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAX 20

int top = -1;
char stack[MAX];
char pop();
void push(char);

main()
{
char str[20];
unsigned int i;
printf(“Enter the string : ” );
gets(str);
/*Push characters of the string str on the stack */
for(i=0;i<strlen(str);i++)
push(str[i]);
/*Pop characters from the stack and store in string str */
for(i=0;i
str[i]=pop();
printf(“Reversed string is : “);
puts(str);
}/*End of main()*/

void push(char item)
{
if(top == (MAX-1))
{
printf(“Stack Overflow\n”);
return;
}
stack[++top] =item;
}/*End of push()*/

char pop()
{
if(top == -1)
{
printf(“Stack Underflow\n”);
exit(1);
}
return stack[top–];
}/*End of pop()*/

 

C program for Linked Lists Using Recursion for all operations


/*Linked list using Recursion*/
#include<stdio.h>
#include<stdlib.h>

struct node
{
int info;
struct node *link;
};
struct node *create_list(struct node *start);
void display(struct node *ptr);
void Rdisplay(struct node *ptr);
int length(struct node *ptr);
int sum (struct node *ptr);
int search(struct node *ptr, int item );
struct node *insertLast(struct node *ptr, int value);
struct node *delLast(struct node *ptr );
struct node *reverse(struct node *ptr);

main()
{
struct node *start=NULL;
int choice,data;

while(1)
{
printf(“\n1.Create List\n”);
printf(“\n2.Display\n”);
printf(“\n3.Display in reverse order\n”);
printf(“\n4.Count\n”);
printf(“\n5.Sum of elements\n”);
printf(“\n6.Search\n”);
printf(“\n7.Insert at last\n”);
printf(“\n8.Delete the last node\n”);
printf(“\n9.Reverse the list\n”);
printf(“\n10.Quit\n”);

printf(“\n\nEnter your choice : “);
scanf(“%d”,&choice);
printf(“\n”);
switch(choice)
{
case 1:
start=create_list(start);
break;
case 2:
display(start);
printf(“\n\n”);
break;
case 3:
Rdisplay(start);
printf(“\n\n”);
break;
case 4:
printf(“\nNumber of elements = %d\n\n”,length(start));
break;
case 5:
printf(“\nSum of elements = %d\n\n”,sum(start));
break;
case 6:
printf(“\nEnter the element to be searched : “);
scanf(“%d”,&data);
if( search(start,data) == 1 )
printf(“\nElement present\n\n”);
else
printf(“\nElement not present\n\n”);
break;
case 7:
printf(“\nEnter the element to be inserted : “);
scanf(“%d”,&data);
start=insertLast(start,data);
break;
case 8:
start=delLast(start);
printf(“\nLast node deleted……\n”);
break;
case 9:
start=reverse(start);
break;
case 10:
exit(1);
default:
printf(“\nWrong choice\n”);
}/*End of switch */
}/*End of while */
}/*End of main()*/

struct node *create_list(struct node *start)
{
int i,n,value;
struct node *q,*tmp;
printf(“\nEnter the number of nodes : “);
scanf(“%d”,&n);
start=NULL;
for(i=1;i<=n;i++)
{
printf(“\nEnter the element to be inserted : “);
scanf(“%d”,&value);

tmp= malloc(sizeof(struct node));
tmp->info=value;
tmp->link=NULL;

if(start==NULL) /*If list is empty */
start=tmp;
else
{ /*Element inserted at the end */
q=start;
while(q->link!=NULL)
q=q->link;
q->link=tmp;
}
}
return start;
}/*End of create_list()*/

void display(struct node *ptr)
{
if(ptr==NULL)
return;
printf(“%3d”,ptr->info);
display(ptr->link);
}/*End of display()*/

void Rdisplay(struct node *ptr)
{
if(ptr==NULL)
return;
Rdisplay(ptr->link);
printf(“%3d”,ptr->info);
}/*End of Rdisplay()*/

int length(struct node *ptr)
{
if(ptr==NULL)
return 0;
return 1 + length(ptr->link);

}/*End of length()*/

int sum (struct node *ptr)
{
if (ptr == NULL)
return 0;
return ptr->info + sum(ptr->link);
}/*End of sum()*/

int search(struct node *ptr, int item )
{
if(ptr==NULL)
return 0;
if( ptr->info == item )
return 1;
return search(ptr->link, item);
}/*End of search()*/

struct node *insertLast(struct node *ptr, int item)
{
struct node *temp;
if (ptr == NULL)
{
temp = malloc(sizeof(struct node));
temp->info = item;
temp->link = NULL;
return temp;
}
ptr->link = insertLast(ptr->link, item);
return ptr;
}/*End of insertLast()*/

struct node *delLast(struct node *ptr )
{
if( ptr->link == NULL )
{
free(ptr);
return NULL;
}
ptr->link = delLast(ptr->link);
return ptr;
}/*End of delLast()*/

struct node *reverse(struct node *ptr)
{
struct node *temp;
if( ptr->link == NULL )
return ptr;
temp=reverse(ptr->link);
ptr->link->link=ptr;
ptr->link=NULL;
return temp;
}/*End of reverse()*/

String Pattern Matching in C using pointers


 

Block diagrams of (Left) pattern matching and ...
Block diagrams of (Left) pattern matching and substitution method and (Right) soft pattern matching method. (Photo credit: Wikipedia)

 

String Pattern Matching Program in C using Pointers

 

Its an application of Arrays

 

 

#include<stdio.h>
#include<conio.h>
int match(char*, char*);

main()
{
char a[100], b[100];
int position;

printf(“Enter some text\n”);
gets(a);

printf(“Enter a string to find\n”);
gets(b);

position = match(a, b);

if(position!=-1)
printf(“Found at location %d\n”, position+1);
else
printf(“Not found.\n”);

getch();
}

int match(char *a, char *b)
{
int c;
int position = 0;
char *x, *y;

x = a;
y = b;

while(*a)
{
while(*x==*y)
{
x++;
y++;
if(*x==”||*y==”)
break;
}
if(*y==”)
break;

a++;
position++;
x = a;
y = b;
}
if(*a)
return position;
else
return -1;
}

 

 

 

\n

 

Array Complete Program using C[DATA STRUCTURE]


 

Real (Laplace) spherical harmonics for to (top...
Real (Laplace) spherical harmonics for to (top to bottom) and to (left to right). The negative order harmonics are rotated about the axis by with respect to the positive order ones. (Photo credit: Wikipedia)

 

Here is what I present Before you is a complete array program where all operations of arrays are included eg:-

 

  1. Insertion

  2. Deletion

  3. Searching

  4. Sorting

  5. Dispay

 

#include <stdio.h>
#include <conio.h>
int n; //size of array

int BSearch(int *a,int ITEM)
{
int beg=0,end=n-1;
int mid;

while( beg<=end )
{
mid=(beg+end)/2;
if(a[mid]==ITEM)
return mid;
else if( a[mid] < ITEM )
beg=mid+1;
else
end=mid-1;
}

return -1;
}

void SSort(int *a)
{
int i,j,temp;

for(i=0; i
{
for(j=i+1; j
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

}

void DEL(int *a, int ITEM)
{
int i;
int pos=BSearch(a, ITEM);

if(pos!=-1)
{
for(i=pos; i
a[i]=a[i+1];
n–;
printf(“\n Item Deleted. “);
}
else
printf(“\n Item not found. “);
}

void INS(int *a, int ITEM)
{
int pos,i;

//Finding the proper position for Sorted Array
if(ITEM>a[n-1])
pos=n;
else if(ITEM<a[0])
pos=0;
else
{
for(i=0; i
if(a[i]<=ITEM && a[i+1]>=ITEM)
{
pos=i+1;
break;
}
}

//Shifting of elements to Insert the element.
for(i=n; i>pos; i–)
a[i]=a[i-1];

a[pos]=ITEM;
n++;
printf(“\n Item Inserted. “);
}

void Display(int *a)
{
int i;
for(i=0; i<n; i++)
printf(” %d”,a[i]);
}

int main()
{
int a[100],ch,pos,ITEM,i;

printf(“\n Enter the number of Elements: “);
scanf(“%d”,&n);

printf(“\n Enter the Elements: “);
for(i=0; i<n; i++)
scanf(“%d”,&a[i]);

do
{
printf(“\n ______________________________________ “);
printf(“\n MENU:\n”);
printf(“\n 1. Insert an element. “);
printf(“\n 2. Delete an element. “);
printf(“\n 3. Search for an element. “);
printf(“\n 4. Display elements. “);
printf(“\n 0. Exit. “);
printf(“\n Your Choice: “);
scanf(“%d”,&ch);

switch(ch)
{

case 1: //INSERT
printf(“\n Enter the Item to Insert: “);
scanf(“%d”,&ITEM);

SSort(a);
INS(a,ITEM);
Display(a);

break;

case 2: //DELETE
printf(“\n Enter the Item to Delete: “);
scanf(“%d”,&ITEM);

SSort(a);
DEL(a,ITEM);
Display(a);

break;

case 3: //SEARCH
printf(“\n Enter the Item to Search: “);
scanf(“%d”,&ITEM);

SSort(a);
pos=BSearch(a,ITEM);

if(pos==-1)
printf(“\n Item not Found. “);
else
printf(“\n Item found at %d position. “,pos+1);

break;

case 4: //DISPLAY
printf(“\n The Elements are: “);

SSort(a);
Display(a);

break;

case 0:
printf(“\n Exiting… “);
break;
}

}while(ch!=0);
getch();
}

 

 

C Program to print a linked list in reverse


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

typedef struct linked_list
{
int item;
struct linked_list *next;
}node;

node *create_list();
void print_list(node *);
void print_list_in_reverse(node *);

int main()
{
node *head=NULL;

printf("you can create a list by entering elements press -999 to end\n");
head=create_list();
printf("\n The list is\n");
print_list(head);
printf("\n The list in reverse order is");
print_list_in_reverse(head);
printf("\n");
return 0;
}

node *create_list()
{
int x;
node *temp=NULL;
scanf("%d",&x);
if(x!=-999)
{
temp=(node*)malloc(sizeof(node));
temp->item=x;
temp->next=NULL;
temp->next=create_list();
}
return temp;
}
void print_list(node *p)
{
if(p)
{
printf("%d ",p->item);
print_list(p->next);
}
else
printf("\n");
}

void print_list_in_reverse(node *p)
{
if(p)
{
print_list_in_reverse(p->next);
printf("%d ",p->item);
}
else
printf("\n");
}

Search An Element in Linked List in C


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
                  {
                    int data;
                    struct node*next;
                  };
 void insert(struct node**p,int num)   /*Function for inserting an
element into a list */
 
 {
   if(*p==NULL)
     {
      (*p)=(struct node*)malloc(sizeof(struct node));
      (*p)->next=NULL;
      (*p)->data=num;
     }
   else
    {
     insert(&((*p)->next),num);
    }
 }
 
void display(struct node*p) /*Function for displaying the list*/
 {
   while(p!=NULL)
    {
     printf(“%d “,p->data);
     p=p->next;
    }
 }
 
 
void reverse(struct node**p) /*Function for reversing the list by
recursion */
 {
   struct node*q,*r,*x;
     int d;
     q=(*p);     /*stores the address of the first element */
     x=q;        /*also stores the element of the first element for
counter pourpose */
     d=q->data;  /*stores the data of the first element*/
     r=q->next;  /*stores the address of the second element in the list
*/
      free(q);   /*deletes the first element of the list*/
      if(x==NULL)
                return ;
                else
                  {
                    reverse(&(r));/*Recursive call*/
                    insert(p,d);  /*This function is put in the stack so the first
                                                     will be taken as last element for the new list */
                  }
 }
 
 void main()
 {
  clrscr();
  struct node*p=NULL;
  int n,d,i=0;
   printf(“How many…?”);
   scanf(“%d”,&n);
    while(i++!=n)
     {
      scanf(“%d”,&d);
      insert(&p,d);
     }
  display(p);
  reverse(&p);
  printf(“The reversed list is…”);
  display(p);
  getch();
 }

CPU scheduling (Round Robin) Program in C


#include<stdio.h>
#include<conio.h>
main()
{
  int st[10],bt[10],wt[10],tat[10],n,tq;
  int i,count=0,swt=0,stat=0,temp,sq=0;
  float awt=0.0,atat=0.0;
  clrscr();
  printf(“Enter number of processes:”);
  scanf(“%d”,&n);
  printf(“Enter burst time for sequences:”);
  for(i=0;i<=n;i++)
   {
     scanf(“%d”,&bt[i]);
     st[i]=bt[i];
   }
   printf(“Enter time quantum:”);
   scanf(“%d”,&tq);
   while(1)
   {
     for(i=0,count=0;i<=n;i++)
     {
       temp=tq;
       if(st[i]==0)
       {
  count++;
  continue;
       }
       if(st[i]=>tq)
 st[i]=st[i]-tq;
       else
 if(st[i]>=0)
 {
   temp=st[i];
   st[i]=0;
 }
 sq=sq+temp;
 tat[i]=sq;
     }
     if(n==count)
     break;
   }
   for(i=0;i<=n;i++)
   {
    wt[i]=tat[i]-bt[i];
    swt=swt+wt[i];
    stat=stat+tat[i];
   }
   awt=(float)swt/n;
   atat=(float)stat/n;
   printf(“Process_no Burst time Wait time Turn around time
“);
   for(i=0;i<=n;i++)
    printf(“%d  %d  %d  %d
“,i+1,bt[i],wt[i],tat[i]);
    printf(“Avg wait time is %f
Avg turn around time is %f”,awt,atat);
    getch();
}

Tree Operations – INSERTION ,INORDER , PREORDER , POSTORDER TRAVERSAL in C | Data structure example on Tree Operation in C | C Assignments in Tree Sorting




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

struct node
{
struct node *left;
int data;
struct node *right;
} ;

void main()
{
void insert(struct node **,int);
void inorder(struct node *);
void postorder(struct node *);
void preorder(struct node *);
struct node *ptr;
int will,i,num;
ptr = NULL;
ptr->data=NULL;
clrscr();

printf("
Enter the number of terms you want to add to the tree.
");
scanf("%d",&will);

/* Getting Input */
for(i=0;i
{
printf("
Enter the item");
scanf("%d",&num);
insert(&ptr,num);
}

getch();
printf("

INORDER TRAVERSAL

");
inorder(ptr);
getch();
printf("

PREORDER TRAVERSAL

");
preorder(ptr);
getch();
printf("

POSTORDER TRAVERSAL

");
postorder(ptr);
getch();
}



void insert(struct node **p,int num)
{


if((*p)==NULL)
{ printf("
Leaf node created.");
(*p)=malloc(sizeof(struct node));
(*p)->left = NULL;
(*p)->right = NULL;
(*p)->data = num;
return;
}
else
{ if(num==(*p)->data)
{
printf("

REPEATED ENTRY ERROR
VALUE REJECTED

");
return;
}
if(num<(*p)->data)
{
printf("
Directed to left link.");
insert(&((*p)->left),num);
}
else
{
printf("
Directed to right link.");
insert(&((*p)->right),num);
}
}
return;
}


void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("
Data :%d",p->data);
inorder(p->right);
}
else
return;
}


void preorder(struct node *p)
{
if(p!=NULL)
{
printf("
Data :%d",p->data);
preorder(p->left);
preorder(p->right);
}
else
return;
}


void postorder(struct node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("
Data :%d",p->data);
}
else
return;
}

C Program to demonstrate time functions.


#include <stdio.h>  /* NULL     */
#include <time.h>  /* ctime, asctime   */
 
main()
{
 time_t now;    /* define 'now'. time_t is probably
  * a typedef */
 
 /* Calender time is the number of
  * seconds since 1/1/1970  */
 
 now = time((time_t *)NULL);  /* Get the system time and put it
  * into 'now' as 'calender time' */
 
 printf("%s", ctime(&now));  /* Format data in 'now' 
  * NOTE that 'ctime' inserts a
  * '\n' */
 
 /*********************************************************************/
 
 /* Here is another way to extract the time/date information */
 
 time(&now);
 
 printf("%s", ctime(&now));  /* Format data in 'now'  */
 
 /*********************************************************************/
 
 {
  struct tm *l_time;
 
  l_time = localtime(&now);  /* Convert 'calender time' to
   * 'local time' - return a pointer
   * to the 'tm' structure. localtime
   * reserves the storage for us. */
  printf("%s", asctime(l_time));
 }
 
 /*********************************************************************/
 
 time(&now);
 printf("%s", asctime(localtime( &now  )));
 
 /*********************************************************************/
 
 {
  struct tm *l_time;
  char string[20];
 
  time(&now);
  l_time = localtime(&now);
  strftime(string, sizeof string, "%d-%b-%y\n", l_time);
  printf("%s", string);
 }
 
 
}

chdir Example program in C, chdir Demo in C, program using chdir function in C



 #include<stdio.h>   
#include<dos.h>
#include<stdlib.h>
#include<process.h>

 const char * const path = "d:/popsys/test";  
const char * const file = "lernc.txt";

int main () {
printf ("Changing directory to <%s>\n", path);

if (chdir (path) == -1) {
printf ("chdir failed - %s\n", strerror (errno));
}else {
printf ("chdir done !!!\n");
printf ("directory content of '%s'\n\n", path);
system ("ls -l");
printf ("\n");
printf ("checking the content of '%s'\n", file);
system ("cat lernc.txt");
}
return 0;
}

C Program to Prove Memory allocation for Integer is 2 byte by using array & Pointer





#include<stdio.h>
#include<conio.h>
 
void printarr(int a[]);
void printdetail(int a[]);
void print_usingptr_a(int a[]);

main()
{
int a[5];
int *b;
int *c;
for(int i = 0;i<5;i++)
{
a[i]=i;
}
printarr(a);
*b=2;
b++;
*b=4;
b++;
*b=6;
b++;
*b=8;
b++;
*b=10;
b++;
*b=12;
b++;
a=c; //error
printarr(a);
getch();
}

void printarr(int a[])
{
for(int i = 0;i<5;i++)
{
printf("value in array %d\n",a[i]);
}
}

void printdetail(int a[])
{
for(int i = 0;i<5;i++)
{
printf("value in array %d and address is %16lu\n",a[i],&a[i]);
}
}

void print_usingptr_a(int a[])
{
for(int i = 0;i<5;i++)
{
printf("value in array %d and address is %16lu\n",*a,a);
a++; // increase by 2 bytes
}
}

C Program to TO REVERSE THE GIVEN STRING using Pointers


#include<stdio.h>
#include<conio.h>
void strev(char *str1, char *str2);

main()
{
char *str1, *str2;
printf("\n\n\t PLZ ENTER A STRING...: ");
gets(str1);
strev(str1,str2);
printf("\n\t YOUR THE REVERSED STRING IS...: ");
puts(str2);
getch();
}
void strev(char *str1, char *str2)
{
int i = 0, len = 0, r = 0;
while(*(str1+len)!='')
len++;
for(i=len-1; i>=0; i--)
{
*(str2+r) = *(str1+i);
r++;
}
*(str2+r) = '';
}

Removing spaces and punctuation from a string in C Language


#include<stdio.h>
#include<ctype.h> 

#define BUFFER_LEN 500 /* Length of input buffer */

int main(void)
{
char buffer[BUFFER_LEN]; /* Input buffer */
char *pbuffer1 = buffer; /* Pointer to buffer position */
char *pbuffer2 = buffer; /* Pointer to buffer position */

/* Read a string */
printf("Enter a string of up to %d characters:\n", BUFFER_LEN);
while((*pbuffer1++ = getchar()) != '\n');
*pbuffer1 = ''; /* Append string terminator */
pbuffer1 = buffer; /* Reset pointer to start */
while(*pbuffer1 != '') /* Loop until the end of the string */
{
if(ispunct(*pbuffer1) || isspace(*pbuffer1))
{ /* If it's space or puctuation */
++pbuffer1; /* go to the next character */
continue;
}
else
*pbuffer2++ = *pbuffer1++; /* otherwise, copy the character */
}
*pbuffer2 = ''; /* Append string terminator */
printf("\nWith the spaces and punctuation removed, the string is now:\n%s\n", buffer);
return 0;
}

Pointers Varieties



*************************************************************************************************

(1) int *p;
// p is a pointer to an integer quantity

(2) int *p[10];
// p is a 10-element array of pointers to integer quantities

(3) int (*p)[10];
// p is a pointer to a 10-element integer array

(4) int *p(void);
// p is a function that returns a pointer to an integer quantity

(5) int p(char *a);
// p is a function that accepts an argument which is a pointer to a character returns an
// integer quantity

(6) int *p(char *a);
// p is a function that accepts an argument which is a pointer to a character returns a
// pointer to an integer quantity

(7) int (*p)(char *a);
// p is pointer to a function that accepts an argument which is a pointer to a character
// returns an integer quantity

(8) int (*p(char *a))[10];
// p is a function that accepts an argument which is a pointer to a character returns a
// pointer to a 10-element integer array

(9) int p(char (*a)[]);
// p is a function that accepts an argument which is a pointer to a character array returns
// an integer quantity

(10) int p(char *a[]);
// p is a function that accepts an argument which is a array of pointers to characters
// returns an integer quantity

(11) int *p(char a[]);
// p is a function that accepts an argument which is a character array returns a pointer to
// to an integer quantity

(12) int *p(char (*a)[]);
// p is a function that accepts an argument which is a pointer to a character array returns a
// pointer to an integer quantity

(13) int *p(char *a[]);
// p is a function that accepts an argument which is an array of pointers to characters
// returns a pointer to an integer quantity

(14) int (*p)(char (*a)[]);
// p is pointer to a function that accepts an argument which is a pointer to a character array
// returns an integer quantity

(15) int *(*p)(char (*a)[]);
// p is pointer to a function that accepts an argument which is a pointer to a character array
// returns a pointer to an integer quantity

(16) int *(*p)(char *a[]);
// p is pointer to a function that accepts an argument which is a array of pointers to
// characters returns a pointer to an integer quantity

(17) int (*p[10])(void);
// p is 10-element array of pointers to functions; each function returns an integer quantity

(18) int (*p[10])(char a);
// p is 10-element array of pointers to functions; each function accepts an argument which is
// a character and returns an integer quantity

(19) int *(*p[10])(char a);
// p is 10-element array of pointers to functions; each function accepts an argument which is
// a character and returns a pointer to an integer quantity

(20) int *(*p[10])(char *a);
// p is 10-element array of pointers to functions; each function accepts an argument which is
// a pointer to a character and returns a pointer to an integer quantity

Swapping numbers using call by reference


#include<stdio.h>
 
void swap(int*, int*);
 
main()
{
int x, y;
 
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
 
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
 
swap(&x, &y);
 
printf("After Swapping\nx = %d\ny = %d\n", x, y);
 
return 0;
}
 
void swap(int *a, int *b)
{
int temp;
 
temp = *b;
*b = *a;
*a = temp;
}

C File I/O and Binary File I/O



When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).

For example:

FILE *fp;

To open a file you need to use the fopen function, which returns a FILE pointer. Once you’ve opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode);

In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected. Your users, of course, do not need to do this! It’s just the way quoted strings are handled in C and C++.

The modes are as follows:

r  - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)

Note that it’s possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer.

Here’s a simple example of using fopen:

FILE *fp;
fp=fopen("c:\\test.txt", "r");

This code will open test.txt for reading in text mode. To open a file in a binary mode you must add a b to the end of the mode string; for example, “rb” (for the reading and writing modes, you can add the b either after the plus sign – “r+b” – or before – “rb+”)

To close a function you can use the function

int fclose(FILE *a_file);

fclose returns zero if the file is closed successfully.

An example of fclose is

fclose(fp);

To work with text input and output, you use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. For example:

FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");

It is also possible to read (or write) a single character at a time–this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file:

int fgetc (FILE *fp);

Notice that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you’re at the very end of the file, you can’t get a character value–in this case, fgetc will return “EOF”, which is a constant that indicates that you’ve reached the end of the file. To see a full example using fgetc in practice, take a look at the example here.

The fputc function allows you to write a character at a time–you might find this useful if you wanted to copy a file character by character. It looks like this:

int fputc( int c, FILE *fp );

Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF.

Binary I/O

For binary File I/O you use fread and fwrite.

The declarations for each are similar:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions deal with blocks of memories – usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.

Let’s look at one function to see how the notation works.

fread takes four arguments. Don’t by confused by the declaration of a void *ptr; void means that it is a pointer that can be used for any type variable. The first argument is the name of the array or the address of the structure you want to write to the file. The second argument is the size of each element of the array; it is in bytes. For example, if you have an array of characters, you would want to read it in one byte chunks, so size_of_elements is one. You can use the sizeof operator to get the size of the various datatypes; for example, if you have a variable int x; you can get the size of x with sizeof(x);. This usage works even for structs or arrays. E.g., if you have a variable of a struct type with the name a_struct, you can use sizeof(a_struct) to find out how much memory it is taking up.

e.g.,

sizeof(int);

The third argument is simply how many elements you want to read or write; for example, if you pass a 100 element array, you want to read no more than 100 elements, so you pass in 100.

The final argument is simply the file pointer we’ve been using. When fread is used, after being passed an array, fread will read from the file until it has filled the array, and it will return the number of elements actually read. If the file, for example, is only 30 bytes, but you try to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was reached, use the feof function, which accepts a FILE pointer and returns true if the end of the file has been reached.

fwrite is similar in usage, except instead of reading into the memory you write from memory into a file.

For example,

FILE *fp;
fp=fopen("c:\\test.bin", "wb");
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);