Monday, July 9, 2018

 ; x8086 alp to convert a BCD into its BINARY equivalent
DATA_SEG SEGMENT
    BCD DB 25H                  ; STORAGE FOR A BCD VALUE
    BIN DB ?                    ; STORAGE FOR BINARY VALUE
DATA_SEG ENDS

CODE_SEG SEGMENT
    ASSUME CS:CODE_SEG,DS:DATA_SEG
    START:
    MOV AX,DATA_SEG
    MOV DS,AX
   
    MOV AH,BCD    
    MOV BH,AH
    AND BH,0FH
    AND AH,0F0H
    ROR AH,04
    MOV CL,10
    MOV AL,AH
    AND AX,00FFH
    MUL CL
    ADD AL,BH
    MOV BIN,AL 
    MOV AH,04CH
    INT 21H
    CODE_SEG ENDS
END START

output, variable BIN gets binary value 00011001 = 25 in decimals.

Tuesday, July 3, 2018

Java: Standard Input / Output

case1: input from same line, out in different lines
import java.util.*;

public class Stdio1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        for(int i=0;i<3;i++)
        {
            int a = scan.nextInt();  //Takes input from the same line
            System.out.println(a);   //but gives out each number in separate lines
        }
      
    }
}

case 2: input from same line and output in same line without gap
import java.util.*;

public class Stdio2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        for(int i=0;i<3;i++)
        {
            int a = scan.nextInt();  //Takes input from the same line
            System.out.print(a);   //gives out each number in same line without any space

           
        }
      
    }
}

case 3: input from same line and output in same line , with space
import java.util.*;

public class Stdio3 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        for(int i=0;i<3;i++)
        {
            int a = scan.nextInt();  //Takes input from the same line
            System.out.print(a+" ");   //gives out each number in same line with  space

           
        }
      
    }
}

case 4: Input from different lines and output also on different lines
import java.util.*;

public class Stdio4 {

    public static void main(String[] args) {
        int a=0;
        int arr[] = new int[3];
        Scanner scan = new Scanner(System.in);
        for(int i=0;i<3;i++)
        {
             a = scan.nextInt();  //Takes input from separate lines
             arr[i]=a;

           
        }
        for(int i=0;i<3;i++)
        {
             System.out.println(arr[i]);   //outputs in separate lines also
        }
       
    }
}

case 5 Input from different lines , but output in same line with space
import java.util.*;

public class Stdio5 {

    public static void main(String[] args) {
        int a=0;
        int arr[] = new int[3];
        Scanner scan = new Scanner(System.in);
        for(int i=0;i<3;i++)
        {
             a = scan.nextInt();  //Takes input from separate lines
             arr[i]=a;

           
        }
        for(int i=0;i<3;i++)
        {
             System.out.print(arr[i]+" ");   //outputs in same line with space
        }
       
    }
}


Monday, July 2, 2018

C program to replace a given line in a file



/*This C program is used to replace a specific line in a text file. */

#include <stdio.h>
int main(void) {
    FILE *fp1, *fp2;
    //'filename'is a 40 character string to store filename
    char filename[40];
    char c;
    int del_line, temp = 1;
    //asks user for file name
    printf("Enter file name: ");
    //receives file name from user and stores in 'filename'
    scanf("%s", filename);
    fp1 = fopen(filename, "r");
    //open file in read mode
    c = getc(fp1);
    //print the contents of file .
    while (c != EOF) {
        printf("%c", c);
        c = getc(fp1);
    }
    //ask user for line number to be deleted.
    printf(" Enter line number to be deleted and replaced");
    scanf("%d", &del_line);
    //take fp1 to start point.
    rewind(fp1);
    //open copy.c in write mode
    fp2 = fopen("copy.c", "w");
    c = getc(fp1);
while (c != EOF) {
        if (c == '') {
            temp++;
        }
        //till the line to be deleted comes,copy the content from one file to other
        if (temp != del_line){
        putc(c, fp2);
        }
        else //when the line to be deleted comes
        {
            while ((c = getc(fp1)) != '') {
            }
            //read and skip the line ask for new text
            printf("Enter new text");
            //flush the input stream
            fflush(stdin);
            putc('', fp2);  //put '' in new file
            while ((c = getchar()) != ''){
                putc(c, fp2);
                //take the data from user and place it in new file
                fputs("
                ", fp2);
                temp++;
            }
            //continue this till EOF is encountered
            c = getc(fp1);
            }
        //close both files
        fclose(fp1);
        fclose(fp2);
        //remove original file
        remove(filename);
        //rename new file with old name opens the file in read mode
        rename("copy.c", filename);
        fp1 = fopen(filename, "r");
        //reads the character from file
        c = getc(fp1);
        //until last character of file is encountered
        while (c != EOF){
            printf("%c", c);
            //all characters are printed
            c = getc(fp1);
        }
        //close the file pointer
        fclose(fp1);
        return 0;
} 
}

C program to show how user authentication is done

    /*

     * C program is to illustrate how user authentication is done.

     * Program asks for the user name and password and displays

     * the password as '*' character

     */

    #include <stdio.h>



    void main()

    {

        char password[31], username[31], ch;

        int i;



        printf("Enter User name: ");

        gets(username);

        printf("Enter the password < any exact 30 characters>: ");

        for (i = 0; i < 31; i++)

        {

                ch = getchar();

                password[i] = ch;

                ch = '*' ;

                printf("%c", ch);

        }

            password[i] = '\0';

        /*  Original password can be printed, if needed */

        printf("\n Your password is :");

        for (i = 0; i < 31; i++)

        {

                printf("%c", password[i]);

        }

    }

C program to find nCr and nPr



#include <stdio.h>

long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);

int main()
{
   int n, r;
   long ncr, npr;

   printf("Enter the value of n and r\n");
   scanf("%d%d",&n,&r);

   ncr = find_ncr(n, r);
   npr = find_npr(n, r);

   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);

   return 0;
}

long find_ncr(int n, int r) {
   long result;

   result = factorial(n)/(factorial(r)*factorial(n-r));

   return result;
}

long find_npr(int n, int r) {
   long result;

   result = factorial(n)/factorial(n-r);

   return result;
}

long factorial(int n) {
   int c;
   long result = 1;

   for (c = 1; c <= n; c++)
      result = result*c;

   return result;
}

C to find power of a number using recurrsion

#include <stdio.h>

int power(int n1, int n2);

int main()
{
    int base, powerRaised, result;

    printf("Enter base number: ");
    scanf("%d",&base);

    printf("Enter power number(positive integer): ");
    scanf("%d",&powerRaised);

    result = power(base, powerRaised);

    printf("%d^%d = %d", base, powerRaised, result);
    return 0;
}

int power(int base, int powerRaised)
{
    if (powerRaised != 0)
        return (base*power(base, powerRaised-1));
    else
        return 1;
}

C program to generate graycode

    /*

     * C Program to Convert Binary Code of a Number into its Equivalent

     * Gray's Code without using Recursion

     */

    #include <stdio.h>

    #include <math.h>



    int bintogray(int);



    int main ()

    {

        int bin, gray;



        printf("Enter a binary number: ");

        scanf("%d", &bin);

        gray = bintogray(bin);

        printf("The gray code of %d is %d\n", bin, gray);

        return 0;

    }



    int bintogray(int bin)

    {

        int a, b, result = 0, i = 0;



        while (bin != 0)

        {

            a = bin % 10;

            bin = bin / 10;

            b = bin % 10;

            if ((a && !b) || (!a && b))

            {

                result = result + pow(10, i);

            }

            i++;

        }

        return result;

    }

C program to remove duplicate elements from an array

#include <stdio.h>

int main()
{
    int arr[10], i, j, k, Size;

    printf("\n Please Enter Number of elements in an array  :   ");
    scanf("%d", &Size);

    printf("\n Please Enter %d elements of an Array \n", Size);
    for (i = 0; i < Size; i++)
    {
        scanf("%d", &arr[i]);
       }

    for (i = 0; i < Size; i++)
    {
        for(j = i + 1; j < Size; j++)
        {
            if(arr[i] == arr[j])
            {
                for(k = j; k < Size; k++)
                {
                    arr[k] = arr[k + 1];
                }
                Size--;
                j--;
            }
        }
    }

     printf("\n Final Array after Deleteing Duplicate Array Elements is:\n");
     for (i = 0; i < Size; i++)
      {
         printf("%d\t", arr[i]);
      }
     return 0;
}

C program to draw staircase

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

void staircase(int n) {
    
    char c='#';
    int x=n-1,y=1;

    for(int i=0;i<n;i++)
    {
        for(int j=x;j>0;j--)
      {
        printf(" ");

      }

        x--;

        for(int k=0;k<y;k++)
        {
            printf("%c",c);

        }
            y++;
            if(y==n+1)
            exit(0);
         printf("\n");
    }

}

int main() {
    int n;
    scanf("%i", &n);
    staircase(n);
    return 0;
}






C program to draw pascals triangle



#include <stdio.h>

long factorial(int);

int main()
{
   int i, n, c;

   printf("Enter the number of rows you wish to see in pascal triangle\n");
   scanf("%d",&n);

   for (i = 0; i < n; i++)
   {
      for (c = 0; c <= (n - i - 2); c++)
         printf(" ");

      for (c = 0 ; c <= i; c++)
         printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));

      printf("\n");
   }

   return 0;
}

long factorial(int n)
{
   int c;
   long result = 1;

   for (c = 1; c <= n; c++)
         result = result*c;

   return result;
}

C palindrome test using pointers

/* program tests a string for palindrome using pointer notation */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main(void)
{
  char *palin,c;
  int i=0, count=0;
  printf("Please enter a word \n");
  short int palindrome(char *,int);       /* Function prototype *  has a bug first argument should be char */
  palin = (char*)malloc(20*sizeof(char));
  printf("Enter a word\n");

  do
  {
     c=getchar();
     palin[i]=c;
     i++;
  }while(c != '\n');
  printf("i=%d\n",i );
  i=i-1;
  palin[i]='\0';
  count =i;

  if(palindrome(palin,count)==1)
        printf("Entered word is not a palindrome\n");
  else
        printf("Entered word is  a palindrome\n");


}

short int palindrome(char * palin, int len)
{
    short int i=0,j=0;
    for(i=0;j=len-1,i<len/2;i++,j--)
    {
        if(palin[i]==palin[j])
            continue;
        else
            return(1);
    }
    return(0);

}

C program to Reversing String without using array

//REVERSING A KNOWN STRING without using ARRAYs

/*If you use sizeof()then a char *str and char str[] will return different answers.
char str[] will return the length of the string(including the string terminator)
while char *str will return the size of the pointer(differs as per compiler).


*/

#include<stdio.h>
#include<string.h>
int main()
{

    char *c= "Hello world";
    int n=0,i=0;
    while(*(c+i)!='\0'){
        n++;
        i++;

    }

    for(int i=(n-1);i>=0;i--)
    {
        printf("%c",*(c+i));
    }
return 0;
}

C program to create transpose of a matrix

    /*

     * C program to accept a matrix of order MxN and find its transpose

     */

    #include <stdio.h>



    void main()

    {

        static int array[10][10];

        int i, j, m, n;



        printf("Enter the order of the matrix \n");

        scanf("%d %d", &m, &n);

        printf("Enter the coefiicients of the matrix\n");

        for (i = 0; i < m; ++i)

        {

            for (j = 0; j < n; ++j)

            {

                scanf("%d", &array[i][j]);

            }

        }

        printf("The given matrix is \n");

        for (i = 0; i < m; ++i)

        {

            for (j = 0; j < n; ++j)

            {

                printf(" %d", array[i][j]);

            }

            printf("\n");

        }

        printf("Transpose of matrix is \n");

        for (j = 0; j < n; ++j)

        {

            for (i = 0; i < m; ++i)

            {

                printf(" %d", array[i][j]);

            }

            printf("\n");

        }

    }


C program if character is a Vowel



#include <stdio.h>

int main()
{
  char ch;

  printf("Input a character\n");
  scanf("%c", &ch);

  if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' &&ch <= 'Z'))
{
    if (ch=='a' || ch=='A' || ch=='e' || ch=='E' || ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch== 'u' || ch=='U')
      printf("%c is a vowel.\n", ch);
    else
      printf("%c is a consonant.\n", ch);
  }
  else
    printf("%c is neither a vowel nor a consonant.\n", ch);

  return 0;
}

C program to check if given matrix is a upper triangle

// Function to check matrix is in upper triangular
// form or not.
#include<stdio.h>
int N,N;
int isUpperTriangularMatrix(int mat[N][N])
{
    for (int i = 1; i < N; i++)
        for (int j = 0; j < i; j++)
            if (mat[i][j] != 0)
                return 0;
    return 1;
}

// Driver function.
int main()
{
    int N=N=4;
    int mat[4][4] = { { 1, 3, 5, 3 },
                      { 0, 4, 6, 2 },
                      { 0, 0, 2, 5 },
                      { 0, 0, 0, 6 } };
    if (isUpperTriangularMatrix(mat))
        printf( "Yes");
    else
        printf("No");
    return 0;
}

C program convert a decimal number into binary number using reccursion

    /*

     * C Program to Convert a Number Decimal System to Binary System using Recursion

     */

    #include <stdio.h>



    int convert(int);



    int main()

    {

        int dec, bin;



        printf("Enter a decimal number: ");

        scanf("%d", &dec);

        bin = convert(dec);

        printf("The binary equivalent of %d is %d.\n", dec, bin);



        return 0;

    }



    int convert(int dec)

    {

        if (dec == 0)

        {

            return 0;

        }

        else

        {

            return (dec % 2 + 10 * convert(dec / 2));

        }

    }

C program passing 2D array

/* When both dimensions are available globally (either as a macro or as a global constant).*/
#include <stdio.h>
const int M = 3;
const int N = 3;

void print(int arr[M][N])
{
    int i, j;
    for (i = 0; i < M; i++)
      for (j = 0; j < N; j++)
        printf("%d ", arr[i][j]);
}

int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    //int arr[][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};  // error : variable-sized object may not be initialized
    print(arr);
   // print(&arr[0][0]); //works with warning expected 'int(*)[(sizetype)N]' but argument is of type ' int *'
    //print((int *)arr); //works with warning expected 'int(*)[(sizetype)N]' but argument is of type ' int *'
   // print((int*)arr[0][0]); // error : abrupt termination of program
    return 0;
}

C program to count number of bits in a decimal number

#include <stdio.h>

#include<stdint.h>

void main()

{

  unsigned long  long int num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0,no_of_0s=0;
    //int64_t num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0,no_of_0s=0;



    printf("Enter a decimal integer \n");

    scanf("%lld", &num);

    decimal_num = num;

    while (num > 0)

    {

        remainder = num % 2;

        /*  To count no.of 1s */

        if (remainder == 1)

        {

            no_of_1s++;

        }
        else{
            no_of_0s++;
        }

        binary = binary + remainder * base;

        num = num / 2;

        base = base * 10;

    }

    printf("Input number is = %lld\n", decimal_num);

    printf("Its binary equivalent is = %lld\n", binary);

    printf("No.of 1's in the binary number is = %lld\n", no_of_1s);

    printf("No.of bits's in its binary equivalent is = %lld\n", no_of_1s+no_of_0s);
}

C program to insert element in an array

#include <stdio.h>

int main()

{

    int  a[25];

    int  i, j, num, m, t, key, pos;



    printf("Please enter number of elements\n");

    scanf("%d", &num);



    printf("Enter the elements one by one\n");

    for(i=0; i<num; i++)

    {

         scanf("%d", &a[i]);

    }



    printf("Input array elements:\n");

    for(i=0; i<num; i++)

    {

         printf("%d\n", a[i]);

    }



    for(i=0; i< num; i++)

    {

         for(j=i+1; j<num; j++)

         {

               if (a[i] > a[j])

               {

                      t = a[i];

                      a[i] = a[j];

                      a[j] = t;

               }

         }

    }



    printf("Sorted array elements (list):\n");

    for(i=0; i<num; i++)

    {

         printf("%d\n", a[i]);

    }



    printf("Enter the element to be inserted\n");

    scanf("%d",&key);



    for(i=0; i<num; i++)

    {

         if ( key < a[i] )

        {

               pos = i;

               break;

        }

    }



    m = num - pos + 1 ;



    for(i=0; i<= m ; i++)

    {

           a[num-i+2] = a[num-i+1] ;

    }



    a[pos] = key;



    printf("Array elements (list) after inserting:\n");

    for(i=0; i<num+1; i++)

    {

          printf("%d\n", a[i]);

    }

}

C program to find LCM and HCF



#include <stdio.h>

int main() {
  int a, b, x, y, t, gcd, lcm;

  printf("Enter two integers\n");
  scanf("%d%d", &x, &y);

  a = x;  // 34
  b = y;   //4

  while (b != 0) {
    t = b;    // t =12,5
    b = a % b;    // b= 65/12=0,2
    a = t;    // a= 12,5
  }

  gcd = a;
  lcm = (x*y)/gcd;

  printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
  printf("Least common multiple of %d and %d = %d\n", x, y, lcm);

  return 0;
}

C program to find frequency of each element in array

/**
 * C program to count frequency of each element of array
 */

#include <stdio.h>

int main()
{
    int arr[100], freq[100];
    int size, i, j, count;

    /* Input size of array */
    printf("Enter size of array: ");
    scanf("%d", &size);

    /* Input elements in array */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);

        /* Initially initialize frequencies to -1 */
        freq[i] = -1;
    }


    for(i=0; i<size; i++)
    {
        count = 1;
        for(j=i+1; j<size; j++)
        {
            /* If duplicate element is found */
            if(arr[i]==arr[j])
            {
                count++;

                /* Make sure not to count frequency of same element again */
                freq[j] = 0;
            }
        }

        /* If frequency of current element is not counted */
        if(freq[i] != 0)
        {
            freq[i] = count;
        }
    }

    /*
     * Print frequency of each element
     */
    printf("\nFrequency of all elements of array : \n");
    for(i=0; i<size; i++)
    {
        if(freq[i] != 0)
        {
            printf("%d occurs %d times\n", arr[i], freq[i]);
        }
    }

    return 0;
}

C program to generate Fibonacci Numbers

     /*

     * C program to generate Fibonacci Series. Fibonacci Series

     * is 0 1 1 2 3 5 8 13 21 ...

     */

    #include <stdio.h>



    void main()

    {

        int  fib1 = 0, fib2 = 1, fib3, limit, count = 0;



        printf("Enter the limit to generate the Fibonacci Series \n");

        scanf("%d", &limit);

        printf("Fibonacci Series is ...\n");

        printf("%d\n", fib1);

        printf("%d\n", fib2);

        count = 2;

        while (count < limit)

        {

            fib3 = fib1 + fib2;

            count++;

            printf("%d\n", fib3);

            fib1 = fib2;

            fib2 = fib3;

        }

    }

C program to draw Dimond pattern



#include <stdio.h>

int main()
{
  int n, c, k, space = 1;

  printf("Enter number of rows\n");
  scanf("%d", &n);

  space = n - 1;

  for (k = 1; k <= n; k++)
  {
    for (c = 1; c <= space; c++)
     {

      printf(" ");
     }

    space--;

    for (c = 1; c <= 2*k-1; c++)
     {

      printf("*");
     }

    printf("\n");
  }

  space = 1;

  for (k = 1; k <= n - 1; k++)
  {
    for (c = 1; c <= space; c++)
      printf(" ");

    space++;

    for (c = 1 ; c <= 2*(n-k)-1; c++)
      printf("*");

    printf("\n");
  }

  return 0;
}

C program to draw a Digonal of entered numbre

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

void staircase(int n) {
   
    char c='#';


        for(int j=n;j>0;j--)
      { printf("%*c\n",j,c);

      }


}

int main() {
    int n;
    scanf("%i", &n);
    staircase(n);
    return 0;
}

C program to count number of lines in a file

#include <stdio.h>
#define MAX_FILE_NAME 100

int main()
{
    FILE *fp;
    int count = 0;  // Line counter (result)
    char filename[MAX_FILE_NAME];
    char c;  // To store a character read from file

    // Get file name from user. The file should be
    // either in current folder or complete path should be provided
    printf("Enter file name: ");
    scanf("%s", filename);

    // Open the file
    fp = fopen(filename, "r");

    // Check if file exists
    if (fp == NULL)
    {
        printf("Could not open file/file does not exist %s", filename);
        return 0;
    }

    // Extract characters from file and store in character c
    for (c = getc(fp); c != EOF; c = getc(fp))
        if (c == '\n') // Increment count if this character is newline
            count = count + 1;

    // Close the file
    fclose(fp);
    printf("The file %s has %d lines\n ", filename, count);

    return 0;
}

C program to count number of letters in a word

#include<stdio.h>

int main(){
    int count=0,i=0;
printf("Type a word  ");
char word[50];
scanf("%s",&word);
printf("\nYou typed the word  \'%s\' \n",word);
while(word[i]!='\0'){
    count++;
    i++;
}
printf("\nTotal number of letters in %s are %d\n",word,count);
return 0;
}

C program to concatanate Strings



#include <stdio.h>

void concatenate(char [], char []);

int main()
{
   char p[100], q[100];

   printf("Input a string\n");
   gets(p);

   printf("Input a string to concatenate\n");
   gets(q);

   concatenate(p, q);

   printf("String obtained on concatenation: \"%s\"", p);

   return 0;
}

void concatenate(char p[], char q[]) {
   int c, d;

   c = 0;

   while (p[c] != '\0') {
      c++;
   }

   d = 0;

   while (q[d] != '\0') {
      p[c] = q[d];
      d++;
      c++;
   }

   p[c] = '\0';
}

C program to check if number is Palindrome

#include <stdio.h>
int main()
{
    int n, reversedInteger = 0, remainder, originalInteger;

    printf("Enter an integer: ");
    scanf("%d", &n);

    originalInteger = n;

    // reversed integer is stored in variable
    while( n!=0 )
    {
        remainder = n%10;
        reversedInteger = reversedInteger*10 + remainder;
        n /= 10;
    }

    // palindrome if orignalInteger and reversedInteger are equal
    if (originalInteger == reversedInteger)
        printf("%d is a palindrome.", originalInteger);
    else
        printf("%d is not a palindrome.", originalInteger);

    return 0;
}

C program to check if Leap year

    /*

     * C program to find whether a given year is leap year or not

     */
     #include<stdio.h>

    void main()

    {

        int year;



        printf("Enter a year \n");

        scanf("%d", &year);

        if ((year % 400) == 0)

            printf("%d is a leap year \n", year);

        else if ((year % 100) == 0)

            printf("%d is a not leap year \n", year);

        else if ((year % 4) == 0)

            printf("%d is a leap year \n", year);

        else

            printf("%d is not a leap year \n", year);

    }

C program to check if Prime number and Arstrong Number

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

int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);

int main()
{
    int n, flag;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // Check prime number
    flag = checkPrimeNumber(n);
    if (flag == 1)
        printf("%d is a prime number.\n", n);
    else
        printf("%d is not a prime number.\n", n);

    // Check Armstrong number
    flag = checkArmstrongNumber(n);
    if (flag == 1)
        printf("%d is an Armstrong number.", n);
    else
        printf("%d is not an Armstrong number.",n);
    return 0;
}

int checkPrimeNumber(int n)
{
    int i, flag = 1;

    for(i=2; i<=n/2; ++i)
    {

    // condition for non-prime number
        if(n%i == 0)
        {
            flag = 0;
            break;
        }
    }
    return flag;
}

int checkArmstrongNumber(int number)
{
    int originalNumber, remainder, result = 0, n = 0, flag;

    originalNumber = number;

    while (originalNumber != 0)
    {
        originalNumber /= 10;   //originalNumber = originalNumber/10
        ++n;
    }

    originalNumber = number;

    while (originalNumber != 0)
    {
        remainder = originalNumber%10;
        result += pow(remainder, n);
        originalNumber /= 10;
    }

    // condition for Armstrong number
    if(result == number)
        flag = 1;
    else
        flag = 0;

    return flag;
}

C program for Matrix multiplicatiion

// C program to multiply two square matrices.
#include <stdio.h>
#define N 4

// This function multiplies mat1[][] and mat2[][],
// and stores the result in res[][]
void multiply(int mat1[][N], int mat2[][N], int res[][N])
{
    int i, j, k;
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < N; j++)
        {
            res[i][j] = 0;
            for (k = 0; k < N; k++)
                res[i][j] += mat1[i][k]*mat2[k][j];
        }
    }
}

int main()
{
int mat1[N][N]=   { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};

int mat2[N][N] = {  {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};

    int res[N][N]; // To store result
    int i, j;
    multiply(mat1, mat2, res);

    printf("Result matrix is \n");
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < N; j++)
           printf("%d ", res[i][j]);
        printf("\n");
    }

    return 0;
}

C program to check if number is Automorphic

#include<stdio.h>
  int main()
  {
    long int n,num,sqr,rem=0;
    int temp,ans;
    printf("Enter a number: ");
    scanf("%ld",&n);
    num=n;
    sqr=n*n;
    temp=10;
    printf("square of %ld is %ld ",n,sqr);
    while(n>0)
    {
       rem=sqr%temp;   //gives units place digit of square of given number
       if(num==rem)
       {
           ans=1;
           break;
      }
      n=n/10;
       temp=temp*10;
    }
    if(ans==1)
    {
       printf("\n %d is automorphic",num);
    }
    else
    {
       printf("\n %d is not automorphic",num);
    }
   return 0;
 }

C: Program to convert Octal number to Decimal equivalent

#include<stdio.h>
#include<math.h>
int main()
{int octal,copy_of_octal,qoutient,number_of_digits=0,copy_of_number_of_digits=0,Decimal_equivalent=0,j=0;
printf("Enter any octal number\n");
scanf("%d",&octal);
copy_of_octal=octal;
while(qoutient!=0)
{
    qoutient=octal/10;
    octal=qoutient;
    number_of_digits++;
}
copy_of_number_of_digits=number_of_digits;
int d[number_of_digits];
while(number_of_digits!=0)
{
    d[j]=copy_of_octal%10;
    copy_of_octal=copy_of_octal/10;
    j++;
    number_of_digits--;
}
for(int k=0;k<copy_of_number_of_digits;k++)
{
     Decimal_equivalent+= d[k]*pow(8,k);

}
 printf("Decimal equivalent of entered octal number is %d ",Decimal_equivalent);
return 0;
}

C : fwrite()

fwrite() function 

Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);

fwrite() function writes the data specified by the void pointer ptr to the file.

ptr: it points to the block of memory which contains the data items to be written.
size: It specifies the number of bytes of each item to be written.
n: It is the number of items to be written.
fp: It is a pointer to the file where data items will be written.

On success, it returns the count of the number of items successfully written to the file. On error, it returns a number less than n. Notice that two arguments (size and n) and return value of fwrite() are of type size_t which on the most system is unsigned int.

To better understand fwrite() function consider the following examples :

Example 1: Writing a variable
float *f = 100.13;

fwrite(&f, sizeof(f), 1, fp);
This writes the value of variable f to the file.

Example 2: Writing an array
int arr[3] = {101, 203, 303};

fwrite(arr, sizeof(arr), 1, fp);
This writes the entire array into the file.
Example 3: Writing some elements of array
int arr[3] = {101, 203, 303};

fwrite(arr, sizeof(int), 2, fp);
This writes only the first two elements of the array into the file.
Example 4: Writing structure
struct student
{
    char name[10];
    int roll;
    float marks;
};

struct student student_1 = {"Tina", 12, 88.123};

fwrite(&student_1, sizeof(student_1), 1, fp);
This writes contents of variable student_1 into the file.
Example 5: Writing array of structure
struct student
{
    char name[10];
    int roll;
    float marks;
};

struct student students[3] = {
                                 {"Tina", 12, 88.123},
                                 {"Jack", 34, 71.182},
                                 {"May", 12, 93.713}
                             };

fwrite(students, sizeof(students), 1, fp);
This writes the whole array students into the file.
Let's say we don't' want to write all elements of the array into the file, instead, we want is to write only 0th and 1st element of the array into the file.
fwrite(students, sizeof(struct student), 2, fp);
Now you have understood how fwrite() function works. Let's create a program using fwrite() function.
The following program demonstrates how to use fwrite() function.
#include<stdio.h>
#include<stdlib.h>

struct employee
{
    char name[50];
    char designation[50];
    int age;
    float salary
} employee;

int main()
{
    int n, i, chars;
    FILE *fp;

    fp = fopen("employee.txt", "wb");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Testing fwrite() function: \n\n");

    printf("Enter the number of records you want to enter: ");
    scanf("%d", &n);

    for(i = 0; i < n; i++)
    {
        printf("\nEnter details of employee %d \n", i + 1);

        fflush(stdin);

        printf("Name: ");
        gets(employee.name);

        printf("Designation: ");
        gets(employee.designation);

        printf("Age: ");
        scanf("%d", &employee.age);

        printf("Salary: ");
        scanf("%f", &employee.salary);

        chars = fwrite(&employee, sizeof(employee), 1, fp);
        printf("Number of items written to the file: %d\n", chars);
    }

    fclose(fp);
    return 0;
}
Expected Output:
Testing fwrite() function:

Enter the number of records you want to enter: 2

Enter details of employee 1
Name: Bob
Designation: Manager
Age: 29
Salary: 34000
Number of items written to the file: 1

Enter details of employee 2
Name: Jake
Designation: Developer
Age: 34
Salary: 56000
Number of items written to the file: 1
How it works ?
In lines 4-10, a structure employee is declared which has four members namely name is an array of characters, designation is also an array of characters, age is of type int and salary is of type float. Along with the structure definition, a variable emp of type struct employee is also declared.
In line 14, three variables n, i and chars are declared of type int.
In line 15, a structure pointer fp of type struct FILE is declared.
In line 17, fopen() function is called with two arguments namely "employee.txt" and "wb". On success, it returns a pointer to file employee.txt and opens the file employee.txt in write-only mode. On failure, it returns NULL.
In lines 19-23, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.
In lines 27-28, the program asks the user how many records he/she wants to enter and stores the number in the variable n.
In lines 30-50, the statements in the for loop asks the user to enter four pieces of information namely name, designation, age and salary. Notice that in line 34 fflush() function is called to flush(remove) the newline character from the standard input which was entered while entering the number of records in line 28. If there had been no call to fflush(stdin) then gets() function in line 37 would have read the newline character from the standard input and doesn't wait for user input. In line 48, fwrite() function is called to write the structure variable emp into the file in binary mode. We already know that on success fwrite() returns the number of items written to the file. Here we are writing the data of a single structure variable so fwrite() will return 1. On error, it will return a number less than 1. The return value of fwrite() is then assigned to the chars variable. In line 49, the printf() statement prints the number of items successfully written to the file.
In line 52, fclose() function is used to close the file.

C program to create, store, update, sort and retrive students database

Sample program:

#include<stdio.h>
#include<stdlib.h>
struct student
{
 int rollno;
 char name[30];
 float mark;
}stud;
//    FUNCTION TO CHECK GIVEN ROLL NO IS AVAILABLE //
int avlrollno(int rno)
{
 FILE *fp;
 int c = 0;
 fp = fopen("Record", "r");
 while (!feof(fp))
 {
  fread(&stud, sizeof(stud), 1, fp);

  if (rno == stud.rollno)
  {
   fclose(fp);
   return 1;
  }
 }
 fclose(fp);
 return 0;
}

//    FUNCTION TO INSERT RECORDS TO THE FILE
void insert()
{
 FILE *fp;
 fp = fopen("Record", "a");
 printf("Enter the Roll no   :");
 scanf("%d", &stud.rollno);
 printf("Enter the Name      :");
 scanf("%s", &stud.name);
 printf("Enter the mark      :");
 scanf("%f", &stud.mark);
 fwrite(&stud, sizeof(stud), 1, fp);
 fclose(fp);
}
//    FUNCTION TO DISPLAY RECORDS
void disp()
{
 FILE *fp1;
 fp1 = fopen("Record", "r");
 printf("\nRoll Number\tName\tMark\n\n");
 while (fread(&stud, sizeof(stud), 1, fp1))
 printf("  %d\t\t%s\t%.2f\n", stud.rollno, stud.name, stud.mark);
 fclose(fp1);
}
//    FUNCTION TO SEARCH THE GIVEN RECORD
void search()
{
 FILE *fp2;
 int r, s, avl;
 printf("\nEnter the Roll no you want to search  :");
 scanf("%d", &r);
 avl = avlrollno(r);
 if (avl == 0)
  printf("Roll No %d is not available in the file\n",r);
 else
 {
  fp2 = fopen("Record", "r");
  while (fread(&stud, sizeof(stud), 1, fp2))
  {
   s = stud.rollno;
   if (s == r)
   {
    printf("\nRoll no = %d", stud.rollno);
    printf("\nName    = %s", stud.name);
    printf("\nMark    = %.2f\n", stud.mark);
   }
  }
  fclose(fp2);
 }
}
//    FUNCTION TO DELETE A RECORD


void deletefile()
{
 FILE *fpo;
 FILE *fpt;
 int r, s;
 printf("Enter the Roll no you want to delete :");
 scanf("%d", &r);
 if (avlrollno(r) == 0)
  printf("Roll no %d is not available in the file\n", r);
 else
 {
  fpo = fopen("Record", "r");
  fpt = fopen("TempFile", "w");
  while (fread(&stud, sizeof(stud), 1, fpo))
  {
   s = stud.rollno;
   if (s != r)
    fwrite(&stud, sizeof(stud), 1, fpt);
  }
  fclose(fpo);
  fclose(fpt);
  fpo = fopen("Record", "w");
  fpt = fopen("TempFile", "r");
  while (fread(&stud, sizeof(stud), 1, fpt))
   fwrite(&stud, sizeof(stud), 1, fpo);
  printf("\nRECORD DELETED\n");
  fclose(fpo);
  fclose(fpt);
 }

}
//    FUNCTION TO UPDATE THE RECORD
void update()
{
 int avl;
 FILE *fpt;
 FILE *fpo;
 int s, r, ch;
 printf("Enter roll number to update:");
 scanf("%d", &r);
 avl = avlrollno(r);
 if (avl == 0)
 {
  printf("Roll number %d is not Available in the file", r);
 }
 else
 {
  fpo = fopen("Record", "r");
  fpt = fopen("TempFile", "w");
  while (fread(&stud, sizeof(stud), 1, fpo))
  {
   s = stud.rollno;
   if (s != r)
    fwrite(&stud, sizeof(stud), 1, fpt);
   else
   {
    printf("\n\t1. Update Name of Roll Number %d", r);
    printf("\n\t2. Update Mark of Roll Number %d", r);
    printf("\n\t3. Update both Name and Mark of Roll Number %d", r);
    printf("\nEnter your choice:");
    scanf("%d", &ch);
    switch (ch)
    {
    case 1:
     printf("Enter Name:");
     scanf("%s", &stud.name);
     break;
    case 2:
     printf("Enter Mark : ");
     scanf("%f", &stud.mark);
     break;
    case 3:
     printf("Enter Name: ");
     scanf("%s", &stud.name);
     printf("Enter Mark: ");
     scanf("%f", &stud.mark);
     break;
    default:
     printf("Invalid Selection");
     break;
    }
    fwrite(&stud, sizeof(stud), 1, fpt);
   }
  }
  fclose(fpo);
  fclose(fpt);
  fpo = fopen("Record", "w");
  fpt = fopen("TempFile", "r");
  while (fread(&stud, sizeof(stud), 1, fpt))
  {
   fwrite(&stud, sizeof(stud), 1, fpo);
  }
  fclose(fpo);
  fclose(fpt);
  printf("RECORD UPDATED");
 }
}
/* FUNCTION TO SORT THE RECORD */
void sort()
{
 int a[20], count = 0, i, j, t, c;
 FILE *fpo;
 fpo = fopen("Record", "r");
 while (fread(&stud, sizeof(stud), 1, fpo))
 {
  a[count] = stud.rollno;
  count++;
 }
 c = count;
 for (i = 0; i<count - 1; i++)
 {
  for (j = i + 1; j<count; j++)
  {
   if (a[i]>a[j])
   {
    t = a[i];
    a[i] = a[j];
    a[j] = t;
   }
  }
 }
 printf("Roll No.\tName\t\tMark\n\n");
 count = c;
 for (i = 0; i<count; i++)
 {
  rewind(fpo);
  while (fread(&stud, sizeof(stud), 1, fpo))
  {
   if (a[i] == stud.rollno)
    printf("\n %d\t\t %s \t\t %2f",stud.rollno, stud.name, stud.mark);
  }

 }
}

//FUNCTION TO CHECK THE FILE IS EMPTY OR NOT
int empty()
{
 int c = 0;
 FILE *fp;
 fp = fopen("Record", "r");
 while (fread(&stud, sizeof(stud), 1, fp))
  c = 1;
 fclose(fp);
 return c;
}
// MAIN PROGRAM
void main()
{
 int c, emp;
  printf("\t Welcome to STUDENT'S DATA CENTER : Choose action");
  //printf("\n\t\t------------------------------------------");
 do
 {
  //printf("\t Welcome to STUDENT'S DATA CENTER : Choose action");
  printf("\n\t\t------------------------------------------");
  printf("\n\t1.INSERT  2.DISPLAY  3.SEARCH");
  printf("  4.DELETE  5.UPDATE  6.SORT");
  printf("  7.EXIT");
  printf("\n\t\t------------------------------------------");
  printf("\nEnter your choice:");
  scanf("%d", &c);
  //printf("\n");
  switch (c)
  {
  case 1:
   insert();
   break;
  case 2:
   emp = empty();
   if (emp == 0)
    printf("\nThe file is EMPTY\n");
   else
    disp();
   break;
  case 3:
   search();
   break;
  case 4:
   deletefile();
   break;
  case 5:
   update();
   break;
  case 6:
   emp = empty();
   if (emp == 0)
    printf("\n The file is EMPTY\n");
   else
    sort();
   break;
  case 7:
   exit(1);
   break;
  default:
   printf("\nYour choice is wrong\nPlease try again...\n");
   break;

  }
 } while (c != 7);


}

Sacred Thought

28 April 2024 Today I am going to explain verse 31 - 38 chapter two for you all. There is no opportunity better than a righteous war (सत्य औ...