Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Showing posts with label C Programming. Show all posts
Showing posts with label C Programming. Show all posts

Thursday, March 2, 2017

Bubble Sort in C language

Bubble Sort

This is a one kind of sorting technique. The complexity of this sorting technique is,
Worst-case performance : O(n^2)
Best-case performance : O(n)
Average-case performance : O(n^2)
For more details click here

Code

/******Bubble Sort*****/

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

//Function defination
int* bubble_sort(int *arr,int *n){
 int i,j,flag,temp;
 for(i=*n-1;i>=0;i--) {
  flag=0;
  for(j=0;j<i;j++)
   if(arr[j]>arr[j+1]){
    //Swapping
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
    flag=1;
   }
  if(flag==0)
   break;
 }
 return arr;
}

//Starting the main function
int main(){
 int *arr,n,i;
 while(1) {
  //Taking the number of element
  printf("\nEnter the number of element you want to store:");
  scanf("%d",&n);
  if(n<=0){
   printf("\nAn array size must be a positive integer.");
   continue;
  }
  else
   break;
 }
 //Creating array dynamically
 arr=(int*)malloc(n*sizeof(int));
 if(!arr){
  printf("\nNot enough memory.");
  exit(0);
 }
 printf("\nEnter the element(s) in the array:");
 for(i=0;i<n;i++){
  printf("\nElement[%d]:",i+1);
  scanf("%d",&arr[i]);
 }
 printf("\nThe element(s) before sorting:");
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 printf("\nThe element(s) after sorting:");
 arr=bubble_sort(arr,&n);
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 return 0;
}

Output

Enter the number of element you want to store:7

Enter the element(s) in the array:
Element[1]:6

Element[2]:1

Element[3]:8

Element[4]:4

Element[5]:5

Element[6]:2

Element[7]:3

The element(s) before sorting: 6 1 8 4 5 2 3
The element(s) after sorting: 1 2 3 4 5 6 8

Merge Sort in C language

Merge Sort

This is a one kind of sorting technique. The complexity of this sorting technique is,
Worst-case performance : O(n log n)
Best-case performance : O(n log n)
Average-case performance : O(n log n)
For more details click here

Code

/******Merge Sort*****/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//Function declaration
int* merge(int*,int,int,int);
//Function definition for merge sort
int* merge_sort(int *arr,int left,int right){
 int mid;
 if(right>left){
  mid=(left+right)/2;
  merge_sort(arr, left, mid);
  merge_sort(arr,mid+1,right);
  merge(arr,left,mid+1,right);
 }
 return arr;
}
//Function definition for merge two array
int* merge(int *arr,int left,int mid,int right){
 int *temp,i,x,no_of_element;
 no_of_element=right-left+1;
 x=left;
 temp=(int*)malloc(no_of_element*sizeof(int)); 
 while((left<=mid-1)&&(mid<=right)) {
  if(arr[left]<=arr[mid])  {
   temp[x++]=arr[left];
   left++;
  }
  else  {
   temp[x++]=arr[mid];
   mid++;
  }
 }
 while(left<=mid-1)
  temp[x++]=arr[left++];
 while(mid<=right)
  temp[x++]=arr[mid++];
 for(i=0;i<no_of_element;i++) {
  arr[right]=temp[right];
  right--;
 }
 return arr;
}
//Main function start
int main()
{
 int *arr,n,i;
 while(1){
  //taking the number of element
  printf("\nEnter the number of element you want to store:");
  scanf("%d",&n);
  if(n<=0){
   printf("\nAn array size must be a positive integer.");
   continue;
  }
  else
   break;
 }
 //Creating array dynamically
 arr=(int*)malloc(n*sizeof(int));
 if(!arr){
  printf("\nNot enough memory.");
  exit(0);
 }
 //Taking the element from user
 printf("\nEnter the element(s) in the array:");
 for(i=0;i<n;i++){
  printf("\nElement[%d]:",i+1);
  scanf("%d",&arr[i]);
 }
 //Print the element before sorting
 printf("\nThe element(s) before sorting:");
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 printf("\nThe element(s) after sorting:");
 //Call the function
 arr=merge_sort(arr,0,n-1);
 //Print the sorted array
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 return 0;
}

Output


Enter the number of element you want to store:5

Enter the element(s) in the array:
Element[1]:1

Element[2]:8

Element[3]:3

Element[4]:2

Element[5]:5

The element(s) before sorting: 1 8 3 2 5
The element(s) after sorting: 1 2 3 5 8

Quick Sort in C language

Quick Sort

This is a one kind of sorting technique. The complexity of this sorting technique is,
Worst-case performance : O(n^2)
Best-case performance : O(n log n)
Average-case performance : O(n log n)
For more details click here

Code

/******Quick Sort*****/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//Function definition
int* quick_sort(int *arr,int low,int high){
 int pivot,i,temp,j;
 if(low<high) {
  pivot=arr[low];
  i=low;
  j=high;
 }
 else
  return arr;
 while(i<j){
  while((arr[i]<=pivot)&&(i<high))
   i++;
  while((arr[j]>=pivot)&&(j>low))
   j--;
  if(i<j){
   temp=arr[i];
   arr[i]=arr[j];
   arr[j]=temp;
  }
 }
 temp=arr[low];
 arr[low]=arr[j];
 arr[j]=temp;
 quick_sort(arr,low,j-1);
 quick_sort(arr,j+1,high); 
}
//Main function started
int main(){
 int *arr,n,i;
 while(1){
  //Taking the number of element
  printf("\nEnter the number of element you want to store:");
  scanf("%d",&n);
  if(n<=0){
   printf("\nAn array size must be a positive integer.");
   continue;
  }
  else
   break;
 }
 //Creating the array dynamically
 arr=(int*)malloc(n*sizeof(int));
 if(!arr) {
  printf("\nNot enough memory.");
  exit(0);
 }
 printf("\nEnter the element(s) in the array:");
 for(i=0;i<n;i++){
  printf("\nElement[%d]:",i+1);
  scanf("%d",&arr[i]);
 }
 printf("\nThe element(s) before sorting:");
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 printf("\nThe element(s) after sorting:");
 arr=quick_sort(arr,0,n-1);
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 return 0;
}

Output

Enter the number of element you want to store:7

Enter the element(s) in the array:
Element[1]:5

Element[2]:6

Element[3]:2

Element[4]:88

Element[5]:554

Element[6]:11

Element[7]:36

The element(s) before sorting: 5 6 2 88 554 11 36
The element(s) after sorting: 2 5 6 11 36 88 554

Selection Sort in C language

Selection Sort

This is a one kind of sorting technique. The complexity of this sorting technique is,
Worst-case performance : O(n^2)
Best-case performance : O(n^2)
Average-case performance : O(n^2)
For more details click here

Code

/*****Selection Sort*****/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//Function defination
int* selection_sort(int *arr,int *n){
 int i,j,temp;
 for(i=0;i<*n-1;i++)
  for(j=i+1;j<*n;j++)
   if(arr[i]>arr[j]){
    //Swapping
    temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
   }
 return arr;
}
//Starting the main function
int main(){
 int *arr,n,i;
 while(1){
  //Taking the number of element
  printf("\nEnter the number of element you want to store:");
  scanf("%d",&n);
  if(n<=0){
   printf("\nAn array size must be a positive integer.");
   continue;
  }
  else
   break;
 }
 //Create array dynamically
 arr=(int*)malloc(n*sizeof(int));
 if(!arr){
  printf("\nNot enough memory.");
  exit(0);
 }
 //Taking the element from user
 printf("\nEnter the element(s) in the array:");
 for(i=0;i<n;i++){
  printf("\nElement[%d]:",i+1);
  scanf("%d",&arr[i]);
 }
 //Print the array before sorting
 printf("\nThe element(s) before sorting:");
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 printf("\nThe element(s) after sorting:");
 //Call the sorting function
 arr=selection_sort(arr,&n);
 //Print the sorted array
 for(i=0;i<n;i++)
  printf(" %d",arr[i]);
 return 0;
}

Output

Enter the number of element you want to store:7

Enter the element(s) in the array:
Element[1]:2

Element[2]:4

Element[3]:1

Element[4]:5

Element[5]:8

Element[6]:7

Element[7]:3

The element(s) before sorting: 2 4 1 5 8 7 3
The element(s) after sorting: 1 2 3 4 5 7 8

Monday, February 13, 2017

Heap Sort Using C language

Heap Sort

Heap sort is a one type of sorting algorithm.
Worst-case performance : O(n log n)
Best-case performance : Ώ(n), O(n log n)
Average-case performance : O(n log n)
For more information click here

Code

/*****Heap sort*****/
#include<stdio.h>
//Function declaration
void manage(int *, int);
void heapsort(int *, int, int);
//Main function start
int main(){
 int arr[20]; 
 int i,j,size,tmp,k;
 
 //Taking the number of element
  printf("Enter the number of elements to sort : ");
 scanf("%d",&size);
 
 //Taking the elements from user
 for(i=1; i<=size; i++) {
   printf("Enter %d element : ",i);
   scanf("%d",&arr[i]);
   manage(arr,i);
 }
 j=size;
 for(i=1; i<=j; i++) {
   //Swap
   tmp=arr[1];
   arr[1]=arr[size];
   arr[size]=tmp;
   size--;
   
   //Function call for heap sort
   heapsort(arr,1,size);
 }
 printf("\nAfter sorting the elements are: ");
 size=j;
 for(i=1; i<=size; i++)
     printf(" %d ",arr[i]);
 return 0;
}

//Function definition
void manage(int *arr, int i){
 int tmp; 
 tmp=arr[i];
 while((i>1)&&(arr[i/2]<tmp)) {
   arr[i]=arr[i/2];
   i=i/2;
 }
 arr[i]=tmp;
}

//Function definition
void heapsort(int *arr, int i, int size){
 int tmp,j;
 tmp=arr[i];
 j=i*2;
 while(j<=size) {
   if((j<size)&&(arr[j]<arr[j+1]))
      j++;
   if(arr[j]<arr[j/2]) 
      break;
   arr[j/2]=arr[j];
   j=j*2;
 }
 arr[j/2]=tmp;
}

Output

Enter the number of elements to sort : 7
Enter 1 element : 8
Enter 2 element : 4
Enter 3 element : 6
Enter 4 element : 9
Enter 5 element : 11
Enter 6 element : 2
Enter 7 element : 5

After sorting the elements are:  2  4  5  8  6  9  11

AVL Tree in C language

AVL Tree in C language

Use C programming language to make an AVL tree and display the tree in INORDER formate.

Code

/******AVL tree******/
#include <stdio.h>
#include <stdlib.h>

//Structure for tree
struct AVL 
{
 int data,height;
 struct AVL *left,*right;
};

//Function definition for getting maximum value
int max(int a,int b)
{
 if(a>=b)
  return a;
 else
  return b; 
}

//Function definition for getting the height of the tree
int height(struct AVL **root)
{
 if(*root==NULL)
  return 0;
 return (*root)->height; 
}

//Function definition for getting the balance factor of the tree
int balance(struct AVL **root)
{
 return(height(&((*root)->left))-height(&((*root)->right)));
}

//Function definition for rotate the tree right
void rightrotate(struct AVL **root)
{
 struct AVL *child,*temp;
 child=(*root)->left;
 temp=child->right;
 child->right=*root;
 (*root)->left=temp;
 (*root)->height=max(height(&((*root)->left)),height(&((*root)->right)))+1;
 child->height=max(height(&((*root)->left)),height(&((*root)->right)))+1;
 *root= child;
 
}

//Function definition for rotate the tree left
void leftrotate(struct AVL **root)
{
 struct AVL *child,*temp;
 child=(*root)->right;
 temp=child->left;
 child->left=*root;
 (*root)->right=temp;
 (*root)->height=max(height(&((*root)->left)),height(&((*root)->right)))+1;
 child->height=max(height(&((*root)->left)),height(&((*root)->right)))+1;
  *root=child;
}

//Function definition for creating
void create(struct AVL **root,int d)
{  int bal;
 if(*root==NULL)
 {
   *root=(struct AVL*)malloc(sizeof(struct AVL));
   (*root)->data=d;
   (*root)->height=1;
   (*root)->left=NULL;
   (*root)->right=NULL;
   return; 
 }
 else if(d > (*root)->data)
  create(&((*root)->right),d);
 else if(d < (*root)->data)
  create(&((*root)->left),d);
 else
   printf("item already exist");
 (*root)->height=max(height(&((*root)->left)),height(&((*root)->right)))+1;  
 bal=balance(&(*root));
 if(bal< -1 && d < (*root)->right->data)
 {
  rightrotate(&((*root)->right));
  leftrotate(&(*root));
 }
 if(bal > 1 && d < (*root)->left->data)
  rightrotate(&(*root)); 
 if(bal < -1 && d < (*root)->right->data)
 {
  leftrotate(&(*root));
 }
 if(bal > 1 && d > (*root)->left->data)
 {
  leftrotate(&((*root)->left));
  rightrotate(&(*root));
 }
    
}

//Function definition for inorder traversal
void inorder(struct AVL **root)
{
 if(*root)
 {
  inorder(&((*root)->left));
  printf("%d\t",(*root)->data);
  inorder(&((*root)->right));
 }
}
int main()
{
 struct AVL *root=NULL;
 int ch,d;
 do
 {   
  printf("\n1.create or insert element to AVL tree");
  printf("\n2.inorder display element to tree");
  printf("\n3.exit");
  printf("\nenter ur choice");
  scanf("%d",&ch);
  switch (ch)
  {
   case 1:
    printf("\nenter element to new node");
    scanf("%d",&d);
    create(&root,d);
    break;
   case 2:
    inorder(&root);
    getch();
    break;
   case 3:
    exit(0);
   default:
    printf("invalid choice");   
  }
 }while(1);
 return (0); 
}

Output

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice1

enter element to new node10

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice1

enter element to new node5

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice1

enter element to new node15

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice1

enter element to new node3

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice1

enter element to new node2

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice1

enter element to new node6

1.create or insert element to   AVL tree
2.inorder display element to tree
3.exit
enter ur choice2
2       3       5       6       10      15

Sunday, February 12, 2017

Hashing Using C language

Hashing Using C language

Create a Hash Table in C language and search table elements.

Code

/*****Hashing technique and collision resolution******/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

//Creating structure
struct Hash{
 int info;
 struct Hash *next;
};

//Function declaration
void search(struct Hash *key,int n);
void display(struct Hash *key,int n);
void insert(struct Hash **key,int n);

int main(){
 int n,i,choice;
 struct Hash *key;
 printf("Enter no of key you want to create:\t");
 scanf("%d",&n);
 key=(struct Hash *)calloc(n,sizeof(struct Hash));
 for(i=0;i<n;i++){
 (key+i)->info=i;
 (key+i)->next=NULL;
 }
 display(key,n);
 while(1){
  printf("\nOPTIONS\n");
  printf("1.Insert\n");
  printf("2.Search\n");
  printf("3.Exit\n");
  printf("Enter choice:\t");
  scanf("%d",&choice);
  switch(choice){
    case 1: insert(&key,n);
      display(key,n);
      break;

    case 2: display(key,n);
      search(key,n);
      break;

    case 3: exit(0);
   default: printf("Enter correct option!!!");
  }
 }
}

//Function definition for insert
void insert(struct Hash **key,int n){
  struct Hash *temp;
  int formulae,element;
   temp=(struct Hash *)calloc(1,sizeof(struct Hash));
   printf("Enter the element:\t");
   scanf("%d",&element);
   temp->info=element;
   temp->next=NULL;
   formulae = element % n;
   if ((*key+formulae)->next==NULL)
   (*key+formulae)->next=temp;
   else{
   temp->next=(*key+formulae)->next;
   (*key+formulae)->next=temp;
   }
}
//Function definition for Display
void display(struct Hash *key,int n){
  int i;
  struct Hash *temp;
  printf("Key\tElements");
 for(i=0;i<n;i++){
  temp=(key+i);
  printf("\n");
  while(temp!=NULL){
   printf("%d\t",(temp)->info);
   temp=temp->next;
  }
 }
}
//Function defination for search
void search(struct Hash *key,int n){
 int search_element,key_index,column=1,i=0;
  struct Hash *temp;
  printf("\nEnter the element to search:\t");
  scanf("%d",&search_element);
  key_index=search_element%n;
  temp=(key+key_index)->next;
 while(temp!=NULL){
  if (temp->info==search_element){
   printf("[%d] is present at [%d] row and [%d] column.",search_element,key_index,column);
   i=1;
  }
  temp=temp->next;
  column=column+1;
 }
 if(i==0)
  printf("[%d] is not present in Hash table.",search_element);
}

Output

Enter no of key you want to create:     5
Key     Elements
0
1
2
3
4
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   1
Enter the element:      10
Key     Elements
0       10
1
2
3
4
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   1
Enter the element:      54
Key     Elements
0       10
1
2
3
4       54
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   1
Enter the element:      69
Key     Elements
0       10
1
2
3
4       69      54
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   1
Enter the element:      87
Key     Elements
0       10
1
2       87
3
4       69      54
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   1
Enter the element:      21
Key     Elements
0       10
1       21
2       87
3
4       69      54
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   2
Key     Elements
0       10
1       21
2       87
3
4       69      54
Enter the element to search:    54
[54] is present at [4] row and [2] column.
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   2
Key     Elements
0       10
1       21
2       87
3
4       69      54
Enter the element to search:    21
[21] is present at [1] row and [1] column.
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   2
Key     Elements
0       10
1       21
2       87
3
4       69      54
Enter the element to search:    58
[58] is not present in Hash table.
OPTIONS
1.Insert
2.Search
3.Exit
Enter choice:   3

Thursday, January 19, 2017

Read A Text File Using C

Read a text file using C

Open a text file using C program and read the content of the file.


Code

/*Write a program to read a file*/
#include <stdio.h>
#include <stdlib.h>

int main()
{
 FILE *fp; //Taking a file pointer variable
 char fname[30],ch;

 //Taking a existing file name from the user to read
 printf("\nEnter a file name to read: ");
 gets(fname);

 //Open the file in read mode
 fp=fopen(fname,"r");
 
 //Check the file is corrupted or not
 if(fp==NULL)
 {
  printf("\nFile cannot be access.");
  exit(0);
 }
 if(ferror(fp)!=0)
 {
  printf("\nFile is either corrupted or damaged");
  exit(1);
 }

 //Print the content of the file
 while((ch=getc(fp))!=EOF)
 {
  printf("%c",ch);
 }

 //Close the file
 fclose(fp);

 return 0;
}

Output>

Enter a file name to read: temp.txt
This is a temporary file.
Note:
To read a file you have to create a file first by using any text editor(Notepad) or you can also use the C program to create a file.

C Program to Store Record In A File

C program to store students records in a file

The main purpose of this program is that to store some information in a file from console.

Code

/*Write a program that will read roll, name and marks of several student from the user and store them in a file*/
#include <stdio.h>
#include <stdlib.h>
//Create a structure for store the records for all students
struct student
{
 int roll;
 char name[30];
 int marks;
} s;
int main( ){
 FILE *fp; //Create a file pointer variable
 char fname[20],s2[20];
 int n,i,s1,s3;
 printf("\nEnter a file name to store student record: ");
 gets(fname);
 //Open the file in write mode
 fp=fopen(fname,"w");
 if(fp==NULL){
  printf("\nError:FIle cannot be created. \a");
  exit(0);
 }
 printf("\nEnter the number of student: ");
 scanf("%d",&n);
 //Taking the records of students and store them in the file
 for(i=0;i<n;i++){
  printf("\nFor student no. %d", i+1);
  printf("\nEnter roll: ");
  scanf("%d",&s.roll);
  printf("\nEnter name: ");
  scanf("%s",&s.name);
  printf("\nEnter marks: ");
  scanf("%d",&s.marks);
  fprintf(fp,"%d\t%s\t%d\n",s.roll,s.name,s.marks);
 }
 //Close the file
 fclose(fp);
 //Open the file in read mode
 fp=fopen(fname,"r");
 if(fp==NULL){
  printf("\nError:FIle does not exist. \a");
  exit(0);
 }
 if(ferror(fp)!=0){
  printf("\nError: File is either corrupted or damaged. \a");
  exit(0);
 }

 //Print the content of the file
 for(i=1;i<=n;i++){
  fscanf(fp,"%d\t%s\t%d\n",&s1,&s2,&s3);
  printf("\n%d\t%s\t%d",s1,s2,s3);
 }
 //Close the file
 fclose(fp);
 return(0);
}

Output

Enter a file name to store student record: student.txt
Enter the number of student: 3
For student no. 1
Enter roll: 101
Enter name: Alex
Enter marks: 85
For student no. 2
Enter roll: 102
Enter name: Rose
Enter marks: 96
For student no. 3
Enter roll: 103
Enter name: Charls
Enter marks: 93
The content of the file is:
101     Alex    85
102     Rose    96
103     Charls  93

Replace A Word In A File

Replace a word in a file

Find a specific word from an existing file and replace that word with another.

Code

/******Word replace in a file******/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
 FILE *fp,*fp1;
 char str[15],str1[15],fname[20],ch;
 int i=0,len,flag,x=0;
 //Creating a file
 printf("\nEnter a file name:");
 gets(fname);
 fp=fopen(fname,"w");
 if(fp==NULL){
  printf("\nFile cannot be created.");
  exit(0);
 }
 if(ferror(fp)!=0){
  printf("\nFile become damage or corrupt.");
  exit(0);
 }
 //Enter the content in the file
 printf("\nEnter the content of the file. press ctrl+z after compulsion.\n\n");
 while((ch=getchar())!=EOF)
  putc(ch,fp);
 fclose(fp);
 //Open the file in read mode
 fp=fopen(fname,"r");
 if(fp==NULL){
  printf("\nFile cannot be created.");
  exit(0);
 }
 if(ferror(fp)!=0){
  printf("\nFile become damage or corrupt.");
  exit(0);
 }
 //Print the content of the file
 printf("\nThe content of the current file is:\n");
 while((ch=getc(fp))!=EOF)
  printf("%c",ch);
 fclose(fp);
 //Open the file in read mode
 fp=fopen(fname,"r");
 if(fp==NULL){
  printf("\nFile cannot be created.");
  exit(0);
 }
 if(ferror(fp)!=0){
  printf("\nFile become damage or corrupt.");
  exit(0);
 }
 //Taking input of the word to be replace
 printf("\nEnter the word you want to replace: ");
 scanf("%s",str);
 len=strlen(str);
 printf("\nEnter replaced word: ");
 scanf("%s",str1);
 //Open a new file to copy all the content of the old file with the replace word
 fp1=fopen("new.txt","w");
 if(fp==NULL){
  printf("\nFile cannot be created.");
  exit(0);
 }
 if(ferror(fp)!=0){
  printf("\nFile become damage or corrupt.");
  exit(0);
 }
 while((ch=getc(fp))!=EOF){
  if((ch!=32) && (ch!='\n')){
   flag=0; 
   i=0;
   do{
    if((ch==str[i]) && (i<len))
     i++;
    else{
     flag=1;
     break;
    }   
   }while(((ch=getc(fp))!=EOF) && (ch!=32) && (ch!='.') && (ch!='\n') && (ch!='?') && (ch!='!'));
  
   if(flag==0){
    fprintf(fp1,"%s",str1);
    if(ch==32) putc(ch,fp1);
    if(ch=='\n') putc(ch,fp1);
    if(ch=='?') fprintf(fp1,"%c ",ch);
    if(ch=='!') fprintf(fp1,"%c ",ch);
    if(ch=='.') fprintf(fp1,"%c ",ch);
    x++;
   }
   else{
    if(i!=0)
     fseek(fp,-(i+1),SEEK_CUR);
    do{
     putc(ch,fp1);
    }while(((ch=getc(fp))!=EOF) && (ch!=32) && (ch!='.') && (ch!='\n') && (ch!='?') && (ch!='!'));
    if(ch==32) putc(ch,fp1);
    if(ch=='\n') putc(ch,fp1);
    if(ch=='?') fprintf(fp1,"%c ",ch);
    if(ch=='!') fprintf(fp1,"%c ",ch);
    if(ch=='.') fprintf(fp1,"%c ",ch);
   }
  }
 }
 printf("\n%d word(s) are found and replace successfully.",x);
 fclose(fp);
 fclose(fp1);

 fp1=fopen("new.txt","r");
 printf("\nThe content of the new file is:\n");
 while((ch=getc(fp1))!=EOF)
  printf("%c",ch);
 
 fclose(fp1);
 return 0;
}

Output


Enter a file name:temp.txt
Enter the content of the file. press ctrl+z after compulsion.
This is a temp file. This file is for testing.
^Z
The content of the current file is:
This is a temp file. This file is for testing.
Enter the word you want to replace: file
Enter replaced word: program
2 word(s) are found and replace successfully.
The content of the new file is:
This is a temp program. This program is for testing.

C Program to Count From A File

C program to count from a file

Count the numbers of characters, vowels, consonant, lines, words, punctuation marks from a existing file.


Code

/*Write a program that will read the contains of a file and count the characters, vowels, consonant, lines, words, punctuation marks */
#include <stdio.h>
#include <stdlib.h>

int main()
{
 FILE *fp;
 char fname[30],ch;
 int c=0,v=0,ln=0,w=0,p=0;

 //Taking a file name from the user
 printf("\nEnter a file name to read: ");
 gets(fname);

 //Open the file in read mode
 fp=fopen(fname,"r");
 
 //Check is the file exist or not
 if(fp==NULL)
 {
  printf("\nFile cannot be access.");
  exit(0);
 }

 //Print the content of the file
 printf("\nThe contain of the file is: \n");
 while((ch=getc(fp))!=EOF)
 {
  printf("%c",ch);
  
  //Checking and count the outputs
  if((ch>=65&&ch<=90)||(ch>=97&&ch<=122))
  {
   c=c+1;
  }
  if((ch=='a')||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u')||(ch=='A')||(ch=='E')||(ch=='I')||(ch=='O')||(ch=='U'))
  {
   v=v+1;
  }
  if((ch=='.')||(ch=='?')||(ch=='!'))
  {
   ln=ln+1;
   w=w+1;
  }
  if(ch==' ')
  {
   w=w+1;
  }
  if((ch==';')||(ch=='"')||(ch==','))
  {
   p=p+1;
  }
 }
 //Print the outputs
 printf("\nNumber of character in the file is %d",c);  //Count the characters
 printf("\nNumbers of vowels in the file is %d",v);               //Count the vowels
 printf("\nNumbers of consonant in the file is %d",(c-v));       //Count the consonants
 printf("\nNumbers of lines in the file is %d",ln);              //Count the lines
 printf("\nNumbers of words in the file is %d",w);               //Count the words
 printf("\nNumbers of punctuation marks in the file is %d",p);   //Count the punctuation marks
 fclose(fp);

 return 0;
}

Output

Enter a file name to read: temp.txt

The containt of the file is:
This is a temporary file.

Number of charecter in the file is 20
Numbers of vouls in the file is 8
Numbers of consonent in the file is 12
Numbers of lines in the file is 1
Numbers of words in the file is 5
Numbers of punchuation marks in the file is 0

Monday, January 16, 2017

Create File In C

Create file in C

Create a text file in C and enter some content in it and close the file.


Code

/****Write a program to create a file****/
#include <stdio.h>
#include <stdlib.h>

int main()
{

 FILE *fp; //Taking a file pointer variable
 char fname[30],ch;

 //Taking a file name from the user with its extension
 printf("\nEnter a file name: ");
 gets(fname);

 //Open the file in write mode
 fp=fopen(fname,"w");
 if(fp==NULL)
 {
  printf("\nFile cannot be created.");
  exit(0);
 }

 //Write the content from the console to the file
 printf("\nEnter contain of the file: \n");
 while((ch=getchar())!=EOF)
 {
  putc(ch,fp);
 }

 printf("\nFile created successfully.");
 //Close the file
 fclose(fp);

 return 0;
}

Output

Enter a file name: temp.txt

Enter contain of the file:
This is a temporary file.
^Z

File created successfully.

Saturday, April 2, 2016

Boundary Fill C Program Using graphics.h

Boundary Fill Algorithm

Unlike Flood Fill Algorithm, Boundary Fill Algorithm starts at a point inside a region and paint the interior outward toward the boundary. If the boundary is specified in a single color, the fill algorithm proceeds outward pixel by pixel until the boundary color is encountered. This method, called the boundary-fill algorithm.

Follow The Instructions To Successfully Run The Program In Dev-Cpp/CodeBlock:

Whenever you #include <graphics.h> in a program, you must instruct the linker to 
link in certain libraries. The command to do so from Dev-C++ is Alt-P. Choose the 
Parameters tab from the pop-up window and type the following into the Linker area:

-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32

Code

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

/* fc = fill color and bc = boundary color */
void boundaryfill(int x, int y, int fc, int bc)
{
    int c = getpixel(x, y);
    if (c != fc && c != bc) {
        putpixel(x, y, fc);
        boundaryfill(x, y + 1, fc, bc);
        boundaryfill(x, y - 1, fc, bc);
        boundaryfill(x - 1, y, fc, bc);
        boundaryfill(x + 1, y, fc, bc);
    }
}

int main()
{
    int arr[] = {10, 10, 100,10, 10, 100, 10, 10};
    initwindow(300,300,"BoundaryFill");
    drawpoly(4, arr);
    
    delay(3000);
    
    boundaryfill(40, 40, 4, 15);
    
    while(!kbhit());
    
    return 0;
}

Output


Friday, April 1, 2016

Flood Fill C Program Using graphics.h

Flood Fill Algorithm

Sometimes we want to fill in (or recolor) an area that is not defined within a single color boundary. Here is a figure describing the situation.

We can paint such areas by replacing a specified interior color instead of searching for a boundary color value. This approach is called a flood-fill algorithm. We can use either a 4-connected or 8-connected approach,

Follow The Instructions To Successfully Run The Program In Dev-Cpp/CodeBlock:

Whenever you #include <graphics.h> in a program, you must instruct the linker to 
link in certain libraries. The command to do so from Dev-C++ is Alt-P. Choose the 
Parameters tab from the pop-up window and type the following into the Linker area:

-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32

Code

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


/* oc = old color and fc = fill color */
void floodfill(int x, int y, int fc, int oc)
{
    int c = getpixel(x, y);
    if (c == oc) {
        putpixel(x, y, fc);
        floodfill(x, y + 1, fc, oc);
        floodfill(x, y - 1, fc, oc);
        floodfill(x - 1, y, fc, oc);
        floodfill(x + 1, y, fc, oc);
    }
}

int main()
{
    int arr[] = {10, 10, 100,10, 10, 100, 10, 10};
    initwindow(300,300,"FloodFill");
    drawpoly(4, arr);
    
    delay(3000);
    
    floodfill(40, 40, 4, 0);
    
    while(!kbhit());
    
    return 0;
}

Output


Friday, March 18, 2016

DDA Line Drawing C Program Using graphics.h

DDA Line Drawing C Program

Digital differential analyzer (DDA) is a floating-point operation based computer line drawing algorithm.

Follow The Instructions To Successfully Run The Program In Dev-Cpp/CodeBlock:

Whenever you #include <graphics.h> in a program, you must instruct the linker to 
link in certain libraries. The command to do so from Dev-C++ is Alt-P. Choose the 
Parameters tab from the pop-up window and type the following into the Linker area:

-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32


Note: for loops in the program is written using -std=c99 or -std=gnu99 syntex.

Code

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

void dda(int x1, int y1, int x2, int y2)
{
    initwindow(500, 500, "DDA");
    int step, xInc, yInc, x, y, dx, dy;
    dx = x2 - x1; dy = y2 - y1;
    step = (abs(dx) > abs(dy))? dx : dy;
    xInc = dx / step; 
    yInc = dy / step;
    x = x1; 
    y = y1;
    putpixel(round(x), round(y), 1);
    
    for (int i = 0; i < step; i++) {
        x += xInc; y += yInc;
        putpixel(round(x), round(y), 1);
    }
}

int main()
{
    int x1,y1, x2, y2;
    printf("Enter The Points:\n");
    printf("(x1,y1): ? ");
    scanf("%d%d",&x1,&y1);
    printf("(x2,y2): ? ");
    scanf("%d%d",&x2,&y2);
    dda(x1,y1,x2,y2);
    while(!kbhit());
    return 0;
}

Output



Saturday, March 5, 2016

FCFS CPU Scheduling Algorithm

FCFS Scheduling Algorithm

First Come First Serve is a CPU scheduling algorithm where CPU execute each process according there appearance.

Code

/****Scheduling algorithm for FCFS****/
#include <stdio.h>
#include >malloc.h<

int main()
{
	int n,*b,*w,i,j,h;
	float avg =0;
	
	printf("\nEnter number of jobs:");
	scanf("%d",&n);
	
	//Create an dynamic array for specified job
	b=(int *)malloc(n*sizeof(int)); //Array for holding the burst time of the jobs
	w=(int *)malloc(n*sizeof(int)); //Array for holding the waiting time of the jobs
	
	//Taking the burst time from the user
	printf("\nEnter the burst time for corresponding jobs:");
	for(i=0;i<n;i++)
	{
		printf("\nProcess %d:",i+1);
		scanf("%d",&b[i]);
	}
	
	w[0]=0;
	printf("\nProcess 1 waiting time is 0"); //First process waiting time is always 0
	for(i=1;<i++)
	{
		w[i]=b[i-1]+w[i-1]; //Calculate the waiting time of the ith process
		printf("\nProcess %d waiting time is %d",i+1,w[i]); //Print the waiting time for the corresponding process
		avg+=w[i]; //Calculate the total waiting time
	}
	
	printf("\nTotal waiting time:%f",avg); //Print the total waiting time
	printf("\nThe average waiting time:%f",avg); //Print the average waiting time

	return 0;
}

Output

Enter number of jobs:5

Enter the burst time for corresponding jobs:
Process 1:3

Process 2:2

Process 3:5

Process 4:7

Process 5:2

Process 1 waiting time is 0
Process 2 waiting time is 3
Process 3 waiting time is 5
Process 4 waiting time is 10
Process 5 waiting time is 17
Total waiting time:35.000000
The average waiting time:7.000000

Shortest Job First CPU Scheduling | Operating System

SJF Scheduling Algorithm

Shortest Job First is a CPU scheduling algorithm where the CPU execute the process first which have the shorest burst time.

Code

/***Scheduling algorithm for SJF***/
#include <stdio.h>
#include <malloc.h>


int main()
{
 int n,*b,*w,*a,i,j,h,t,tt;
 float avg =0;
 
 printf("\nEnter the numbers of jobs:");
 scanf("%d",&n);
 
 b=(int *)malloc(n*sizeof(int)); //Array for holding the burst time of the jobs
 w=(int *)malloc(n*sizeof(int)); //Array for holding the waiting time of the jobs
 a=(int *)malloc(n*sizeof(int)); //Array for holding the jobs number according their appearance
 
 //Taking the burst time from the user
 printf("\nEnter the burst time for corresponding jobs:");
 for(i=1;i<=n;i++)
 {
  printf("\nProcess %d:",i);
  scanf("%d",&b[i]);
  a[i]=i;
 }
 
 for(i=1;i<=n;i++)
 {
  for(j=i;j<=n;j++)
  {
   //Shorting the process according to their burst time in ascending order
   if(b[i]>b[j]) 
   {
    t=b[i];tt=a[i];
    b[i]=b[j];a[i]=a[j];
    b[j]=t;a[j]=tt;
   }
   
   //If both process has same burst time then short them according their appearance
   if(b[i]==b[j]) 
   {
    if(a[i]>a[j])
    {
     t=a[i];
     a[i]=a[j];
     a[j]=t;
    }
   }
  }
 }
 
 w[1]=0;
 printf("\nProcess %d waiting time is 0",a[1]); //The first process waiting time is always 0
 for(i=2;i<=n;i++)
 {
  w[i]=b[i-1]+w[i-1]; //Calculate the waiting time of the i'th process
  printf("\nProcess %d waiting time is %d",a[i],w[i]); //Print the waiting time
  avg+=w[i]; //Calculate the total waiting time
 }
 
 printf("\nTotal waiting time :%f",avg); //Print the total waiting time
 printf("\nThe average waiting time :%f",avg/n);//Print the average waiting time

 return 0;
}

Output

Enter the numbers of jobs:5

Enter the burst time for corresponding jobs:
Process 1:4

Process 2:3

Process 3:6

Process 4:2

Process 5:1

Process 5 waiting time is 0
Process 4 waiting time is 1
Process 2 waiting time is 3
Process 1 waiting time is 6
Process 3 waiting time is 10
Total waiting time :20.000000
The average waiting time :4.000000

Wednesday, March 2, 2016

C Program For Rotation Using graphics.h

C Program For Rotation Of An Object

We have already described what is Rotation in previous posts. Here is the c code using graphics.h library functions.
Follow The Instructions To Successfully Run The Program:

Whenever you #include <graphics.h> in a program, you must instruct the linker to 
link in certain libraries. The command to do so from Dev-C++ is Alt-P. Choose the 
Parameters tab from the pop-up window and type the following into the Linker area:

-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32


Note: for loops in the program is written using -std=c99 or -std=gnu99 syntex.

Code

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

void print(int a[][3])
{
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

}

void multiply(int a[][3], int b[][3], int c[][3])
{
    int sum = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                sum += (a[i][k] * b[k][j]);
            }
            c[i][j] = sum;
            sum = 0;
        }
    }
}

void rotation(int a[][3])
{
    int deg; 
    float c[3][3], sum = 0.0; 
    float t[3][3];
    printf("Enter The Angel: ");
    scanf("%d",&deg);
        
    t[0][0] = t[1][1] = cos(deg*3.14/180);
    t[0][1] = sin(deg*3.14/180);
    t[1][0] = -t[0][1];
    t[2][2] = 1; t[0][2] = t[2][0] = 0;
    t[2][1] = t[1][2] = 0;
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            printf("%g ", t[i][j]);
        }
        printf("\n");
    }
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                sum += (t[i][k] * a[k][j]);
            }
            c[i][j] = round(sum);
            sum = 0;
        }
    }
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            printf("%g ", c[i][j]);
        }
        printf("\n");
    }
    line(c[0][0], c[1][0], c[0][1], c[1][1]);
    line(c[0][1], c[1][1], c[0][2], c[1][2]);
    line(c[0][2], c[1][2], c[0][0], c[1][0]);
}

int main()
{
    initwindow(600, 600);
    int a[3][3];
    int x1, y1, x2, y2, x3, y3;
    int ch;
    printf("Enter The Initital Points: \n");
    printf("Enter X1, Y1: \n");
    scanf("%d%d",&x1,&y1);
    printf("Enter X2, Y2: \n");
    scanf("%d%d",&x2,&y2);
    printf("Enter X3, Y3: \n");
    scanf("%d%d",&x3,&y3);
    
    line(x1,y1,x2,y2);
    line(x2,y2,x3,y3);
    line(x3,y3,x1,y1);
    
    a[0][0] = x1;
    a[1][0] = y1;

    a[0][1] = x2;
    a[1][1] = y2;

    a[0][2] = x3;
    a[1][2] = y3;

    a[2][0] = a[2][1] = a[2][2] = 1;
    print(a);  
    
    rotation(a);

    while(!kbhit());
    return 0;
}

Output


C Program For Translation Using graphics.h

C Program For Translation Of An Object

We have already described what is translation in previous posts. Here is the c code using graphics.h library functions.

Follow The Instructions To Successfully Run The Program:

Whenever you #include <graphics.h> in a program, you must instruct the linker to 
link in certain libraries. The command to do so from Dev-C++ is Alt-P. Choose the 
Parameters tab from the pop-up window and type the following into the Linker area:

-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32


Note: for loops in the program is written using -std=c99 or -std=gnu99 syntex.

Code

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

void print(int a[][3])
{
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

}

void multiply(int a[][3], int b[][3], int c[][3])
{
    int sum = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                sum += (a[i][k] * b[k][j]);
            }
            c[i][j] = sum;
            sum = 0;
        }
    }
}


void traslation(int a[][3])
{
    int ty, tx;
    int t[3][3], c[3][3];
    
    printf("Enter The Traslation Parameters tx and ty: ");
    scanf("%d%d",&tx, &ty);
    
    t[0][0] = t[1][1] = t[2][2] = 1;
    t[0][2] = tx; t[1][2] = ty;
    t[0][1] = t[1][0] = t[2][0] = t[2][1] = 0;
    print(t);
    multiply(t, a, c);
    
    line(c[0][0], c[1][0], c[0][1], c[1][1]);
    line(c[0][1], c[1][1], c[0][2], c[1][2]);
    line(c[0][2], c[1][2], c[0][0], c[1][0]);
    
    print(c);
}

int main()
{
    initwindow(600, 600);
    int a[3][3];
    int x1, y1, x2, y2, x3, y3;
    int ch;
    printf("Enter The Initital Points: \n");
    printf("Enter X1, Y1: \n");
    scanf("%d%d",&x1,&y1);
    printf("Enter X2, Y2: \n");
    scanf("%d%d",&x2,&y2);
    printf("Enter X3, Y3: \n");
    scanf("%d%d",&x3,&y3);
    
    line(x1,y1,x2,y2);
    line(x2,y2,x3,y3);
    line(x3,y3,x1,y1);
    
    a[0][0] = x1;
    a[1][0] = y1;

    a[0][1] = x2;
    a[1][1] = y2;

    a[0][2] = x3;
    a[1][2] = y3;

    a[2][0] = a[2][1] = a[2][2] = 1;
    print(a);  
    
    traslation(a);

    while(!kbhit());
    return 0;
}

Output


C Program For Scaling Using graphics.h

C Program For Scaling An Object

We have already described what is translation in previous posts. Here is the c code using graphics.h library functions.

Follow The Instructions To Successfully Run The Program:

Whenever you #include <graphics.h> in a program, you must instruct the linker to 
link in certain libraries. The command to do so from Dev-C++ is Alt-P. Choose the 
Parameters tab from the pop-up window and type the following into the Linker area:

-lbgi
-lgdi32
-lcomdlg32
-luuid
-loleaut32
-lole32


Note: for loops in the program is written using -std=c99 or -std=gnu99 syntex.

Code

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

void print(int a[][3])
{
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

}

void multiply(int a[][3], int b[][3], int c[][3])
{
    int sum = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                sum += (a[i][k] * b[k][j]);
            }
            c[i][j] = sum;
            sum = 0;
        }
    }
}


void scaling(int a[][3])
{
    int sx, sy;
    int t[3][3], c[3][3];
    
    printf("Enter The Scaling Parameters tx and ty: ");
    scanf("%d%d",&sx, &sy);
    
    t[0][0] = sx; t[1][1] = sy; t[2][2] = 1;
    t[0][1] = t[1][0] = t[0][2] = t[2][0] = 0;
    t[1][2] = t[2][1] = 0;
    
    print(t);
    multiply(t, a, c);
    print(c);   
    line(c[0][0], c[1][0], c[0][1], c[1][1]);
    line(c[0][1], c[1][1], c[0][2], c[1][2]);
    line(c[0][2], c[1][2], c[0][0], c[1][0]);
    
}
int main()
{
    initwindow(600, 600);
    int a[3][3];
    int x1, y1, x2, y2, x3, y3;
    int ch;
    printf("Enter The Initital Points: \n");
    printf("Enter X1, Y1: \n");
    scanf("%d%d",&x1,&y1);
    printf("Enter X2, Y2: \n");
    scanf("%d%d",&x2,&y2);
    printf("Enter X3, Y3: \n");
    scanf("%d%d",&x3,&y3);
    
    line(x1,y1,x2,y2);
    line(x2,y2,x3,y3);
    line(x3,y3,x1,y1);
    
    a[0][0] = x1;
    a[1][0] = y1;

    a[0][1] = x2;
    a[1][1] = y2;

    a[0][2] = x3;
    a[1][2] = y3;

    a[2][0] = a[2][1] = a[2][2] = 1;
    print(a);  
    
    scaling(a);

    while(!kbhit());
    return 0;
}

Output